Add visibility-aware interval helper

This commit is contained in:
Jonathan Sykes
2026-10-07 03:30:22 +08:00
parent 2e58924971
commit 722df3125f
2 changed files with 131 additions and 0 deletions

41
frontend/visible-timer.js Normal file
View 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);