-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathutil.js
More file actions
42 lines (36 loc) · 1.13 KB
/
util.js
File metadata and controls
42 lines (36 loc) · 1.13 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
export const sleep = (ms) => new Promise((res) => setTimeout(res, ms));
/**
*
* @param {Function} doit Thing to run when user navigates
*/
export const onBrowse = (doit) => {
window.onpopstate = doit;
// https://stackoverflow.com/a/64927639/270302
for (const type of ["pushState", "replaceState"]) {
window.history[type] = new Proxy(window.history[type], {
apply: (target, thisarg, argarray) => {
doit();
return target.apply(thisarg, argarray);
},
});
}
doit();
};
/**
* Waits for a condition to be true and then performs an action.
* Useful for waiting for elements to appear in the DOM.
*
* @param {Function} fetcher A function that returns an element or not
* @param {Function} action A function that is called with the element once it is available
* @param {number} timeout Maximum time to wait for the element (default: 10 seconds)
*/
export const until = (fetcher, action, timeout = 10000) => {
const checker = setInterval(() => {
const element = fetcher();
if (element) {
clearInterval(checker);
return action(element);
}
}, 200);
setTimeout(() => clearInterval(checker), timeout);
};