Extend setTimeout/setInterval with Pause, Resume, and Batch Management
This article shows how to create a global timer object that tracks setTimeout and setInterval IDs, provides batch clearing, adds pause and resume capabilities, and demonstrates framework‑agnostic implementations inspired by CreateJS and PIXI, with full code examples and GitHub references.
Managing setTimeout & setInterval with a Global Timer Object
To keep track of all setTimeout and setInterval calls, the author creates a top‑level timer object that contains two arrays, sto for timeout IDs and siv for interval IDs. var timer = { sto: [], siv: [] }; When a timeout or interval is created, its ID is pushed into the corresponding array:
// mark setTimeout ID
timer.sto.push(setTimeout(function () { console.log("3s"); }, 3000));
// mark setInterval ID
timer.siv.push(setInterval(function () { console.log("1s"); }, 1000));Batch clearing is done by iterating over the stored IDs:
// clear all timeouts
timer.sto.forEach(function (id) { clearTimeout(id); });
// clear all intervals
timer.siv.forEach(function (id) { clearInterval(id); });Pause & Resume Extension
Because many business scenarios need to temporarily suspend and later resume timers, the author adds two methods to the timer object:
// pause all timers
timer.pause();
// resume all timers
timer.resume();After the extension, the timer object exposes six basic APIs:
setTimeout
setInterval
clearTimeout
clearInterval
pause
resume
All native timer calls are replaced with timer.set* and timer.clear*. The implementation is hosted at https://github.com/leeenx/timer.
Inspiration from CreateJS
While working with CreateJS, the author discovered that toggling createjs.Ticker.paused pauses animations driven by createjs.Tween. Using this idea, equivalent setTimeout and setInterval functions are added to the createjs namespace:
// setTimeout
createjs.setTimeout = function (fn, delay) {
createjs.Tween.get().wait(delay).call(fn);
};
// setInterval
createjs.setInterval = function (fn, delay) {
createjs.Tween.get().wait(delay).call(fn).loop = 1;
};The four APIs ( setTimeout, setInterval, clearTimeout, clearInterval) are attached to the createjs object and used just like the native versions:
let siv = createjs.setInterval(() => console.log("1s"), 1000);
createjs.setTimeout(() => createjs.clearInterval(siv), 5000);Framework‑Agnostic Timer Design
To avoid dependence on CreateJS, the author designs a timer that can be driven by any external ticker. The core consists of a queue (a Map) that stores timer entries, an updateQueue function that advances elapsed time, and an external update method that external tickers call.
// queue entry structure
// { fn: callback, type: "timeout"|"interval", elapsed: 0, delay: ms }
let queue = new Map();
function updateQueue(delta) {
queue.forEach((item, id) => {
item.elapsed += delta;
if (item.elapsed >= item.delay) {
item.fn();
// remove timeout, keep interval looping
item.type === "timeout" ? delete queue[id] : (item.elapsed = 0);
}
});
}
this.update = function (delta) {
updateQueue(delta);
};The concrete implementation can be inspected at https://github.com/leeenx/es6-utils#timer.
Using the Timer with CreateJS and PIXI
When integrated with CreateJS, the timer is updated on each tick unless the ticker is paused:
import timer from './modules/timer';
createjs.Ticker.addEventListener("tick", function (e) {
e.paused || timer.update(e.delta);
});With PIXI, the same pattern applies using PIXI's ticker:
import timer from './modules/timer';
app.ticker.add("tick", function () {
timer.update(app.ticker.elapsedMS);
});Conclusion
The author thanks readers and notes that the views expressed are personal opinions intended to help developers facing similar timer‑management challenges.
Signed-in readers can open the original source through BestHub's protected redirect.
This article has been distilled and summarized from source material, then republished for learning and reference. If you believe it infringes your rights, please contactand we will review it promptly.
Aotu Lab
Aotu Lab, founded in October 2015, is a front-end engineering team serving multi-platform products. The articles in this public account are intended to share and discuss technology, reflecting only the personal views of Aotu Lab members and not the official stance of JD.com Technology.
How this landed with the community
Was this worth your time?
0 Comments
Thoughtful readers leave field notes, pushback, and hard-won operational detail here.
