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