/
index.js
71 lines (59 loc) · 1.9 KB
/
index.js
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
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
/**
* Create a timer (similar to setTimeout) that only runs when tab is visible
* @param {function} callback
* @param {number} timeoutMs
* @return {function} stopWaiting - call to abort timer
*/
export default function whileTabVisibleTimeout(callback, timeoutMs) {
let timeoutId;
let cleanupListener;
if (isTabVisible()) {
// Tab started off visible
// Keep track of start time in case we need to pause timeout
const startTime = Date.now();
cleanupListener = whenNotVisible(() => {
// Tab was hidden before timeout completed
clearTimeout(timeoutId);
// Wait until tab is visible again to restart timeout
whileTabVisibleTimeout(callback, timeoutMs - (Date.now() - startTime));
});
// Start timer
timeoutId = setTimeout(() => {
cleanupListener();
callback();
}, timeoutMs);
} else {
// Tab started off hidden
cleanupListener = whenVisible(() => {
// Tab became visible. Start timer now.
whileTabVisibleTimeout(callback, timeoutMs);
});
}
return stopWaiting;
function stopWaiting() {
cleanupListener();
clearTimeout(timeoutId);
}
}
function whenVisible(callback) {
return onVisibilityChange(true, callback);
}
function whenNotVisible(callback) {
return onVisibilityChange(false, callback);
}
function onVisibilityChange(shouldBeVisible, callback) {
document.addEventListener('visibilitychange', handleVisibilityChange);
return cleanup;
function handleVisibilityChange() {
if (shouldBeVisible === isTabVisible()) {
cleanup();
callback();
}
}
function cleanup() {
document.removeEventListener('visibilitychange', handleVisibilityChange);
}
}
function isTabVisible() {
return document.visibilityState === 'visible';
}