I create different timer with setTimeout()
function in different class. I want to know if there is a way to get all timeouts together?
Asked
Active
Viewed 5,327 times
6

T.J. Crowder
- 1,031,962
- 187
- 1,923
- 1,875

Polly
- 637
- 3
- 12
- 25
-
You cannot do that. The `setTimeout()` and `setInterval()` functions return values, but you have to keep track of them with your own code. – Pointy Sep 02 '17 at 13:01
-
How about using a static implementation of setTimeOut()? THis can be called from all classes and also calls can be tracked. – user1615664 Sep 02 '17 at 13:03
-
You have to store return id somewhere in common array then you can check that – Yogesh Sep 02 '17 at 13:03
-
You may find the answers and packages mentioned here useful: https://stackoverflow.com/q/26057328/3412775 – Tomty Nov 30 '20 at 15:44
2 Answers
5
Not by default, no. You could make your own module that lets you keep track of the timers, and which gives you the list. Roughly:
// ES2015+ version
const activeTimers = [];
exports.setTimeout = (callback, interval, ...timerArgs) => {
const handle = setTimeout((...args) => {
const index = activeTimers.indexOf(handle);
if (index >= 0) {
activeTimers.splice(index, 1);
}
callback(...args);
}, interval, ...timerArgs);
activeTimers.push(handle);
};
exports.getActiveTimers = () => {
return activeTimers.slice();
};
...then use its setTimeout
instead of the global one.

T.J. Crowder
- 1,031,962
- 187
- 1,923
- 1,875
2
There's no API to get registered timeouts, but there's a "way" to achieve your goal.
Create a new function, let's call it registerTimeout
. Make sure it has the same signature as setTimeout
. In this function, keep track of what you need (returned timer id, callback function, timeout period...) and register using setTimeout
.
Now you can query your own data structure for registered timeouts.
Of course you should probably keep track of expired / triggered timeouts as well as cleared timeouts...

Amit
- 45,440
- 9
- 78
- 110