Add visibility-aware interval helper
This commit is contained in:
41
frontend/visible-timer.js
Normal file
41
frontend/visible-timer.js
Normal file
@@ -0,0 +1,41 @@
|
||||
(function (root) {
|
||||
'use strict';
|
||||
|
||||
function setIntervalWhenVisible(fn, ms, { immediate = false } = {}) {
|
||||
if (typeof fn !== 'function') throw new TypeError('fn must be a function');
|
||||
const doc = root.document;
|
||||
if (!doc) throw new Error('document is required');
|
||||
|
||||
let timer = null;
|
||||
let stopped = false;
|
||||
const clear = () => {
|
||||
if (timer !== null) root.clearInterval(timer);
|
||||
timer = null;
|
||||
};
|
||||
const start = (runNow) => {
|
||||
if (stopped || doc.hidden) return;
|
||||
clear();
|
||||
if (runNow) fn();
|
||||
timer = root.setInterval(fn, ms);
|
||||
};
|
||||
const onVisibilityChange = () => {
|
||||
if (doc.hidden) clear();
|
||||
else start(immediate);
|
||||
};
|
||||
|
||||
if (!doc.hidden) start(immediate);
|
||||
doc.addEventListener('visibilitychange', onVisibilityChange);
|
||||
return {
|
||||
clear() {
|
||||
if (stopped) return;
|
||||
stopped = true;
|
||||
clear();
|
||||
doc.removeEventListener('visibilitychange', onVisibilityChange);
|
||||
},
|
||||
};
|
||||
}
|
||||
|
||||
const api = { setIntervalWhenVisible };
|
||||
if (typeof module !== 'undefined' && module.exports) module.exports = api;
|
||||
else root.VisibleTimer = api;
|
||||
})(globalThis);
|
||||
Reference in New Issue
Block a user