| 1 |
import isBrowser from './isBrowser'; |
| 2 |
|
| 3 |
const timeoutDuration = (function(){ |
| 4 |
const longerTimeoutBrowsers = ['Edge', 'Trident', 'Firefox']; |
| 5 |
for (let i = 0; i < longerTimeoutBrowsers.length; i += 1) { |
| 6 |
if (isBrowser && navigator.userAgent.indexOf(longerTimeoutBrowsers[i]) >= 0) { |
| 7 |
return 1; |
| 8 |
} |
| 9 |
} |
| 10 |
return 0; |
| 11 |
}()); |
| 12 |
|
| 13 |
export function microtaskDebounce(fn) { |
| 14 |
let called = false |
| 15 |
return () => { |
| 16 |
if (called) { |
| 17 |
return |
| 18 |
} |
| 19 |
called = true |
| 20 |
window.Promise.resolve().then(() => { |
| 21 |
called = false |
| 22 |
fn() |
| 23 |
}) |
| 24 |
} |
| 25 |
} |
| 26 |
|
| 27 |
export function taskDebounce(fn) { |
| 28 |
let scheduled = false; |
| 29 |
return () => { |
| 30 |
if (!scheduled) { |
| 31 |
scheduled = true; |
| 32 |
setTimeout(() => { |
| 33 |
scheduled = false; |
| 34 |
fn(); |
| 35 |
}, timeoutDuration); |
| 36 |
} |
| 37 |
}; |
| 38 |
} |
| 39 |
|
| 40 |
const supportsMicroTasks = isBrowser && window.Promise |
| 41 |
|
| 42 |
|
| 43 |
/** |
| 44 |
* Create a debounced version of a method, that's asynchronously deferred |
| 45 |
* but called in the minimum time possible. |
| 46 |
* |
| 47 |
* @method |
| 48 |
* @memberof Popper.Utils |
| 49 |
* @argument {Function} fn |
| 50 |
* @returns {Function} |
| 51 |
*/ |
| 52 |
export default (supportsMicroTasks |
| 53 |
? microtaskDebounce |
| 54 |
: taskDebounce); |