Implementing the Clear-All Mechanism
Now that we've got a way to keep track of all active timers, implementing the clearAllTimeouts
function becomes a straightforward task.
Leveraging the Set for Mass Cancellation
The core idea is to simply loop through our timers
Set and use the native clearTimeout
function on each timer ID stored in it. This will effectively stop all the timers, and your window will be free from any lingering timing events.
JAVASCRIPT
1const timers = new Set();
2window.nativeSetTimeout = window.setTimeout;
3window.nativeClearTimeout = window.clearTimeout;
4
5// The magic happens here
6window.clearAllTimeouts = () => {
7 for (const id of timers) {
8 window.clearTimeout(id);
9 }
10};
11
12window.setTimeout = (cb, time, ...args) => {
13 const cbWrapper = () => {
14 cb(...args);
15 // No more tracking needed
16 timers.delete(id);
17 };
18 const id = window.nativeSetTimeout(cbWrapper, time);
19 timers.add(id);
20 return id;
21};
22
23window.clearTimeout = (id) => {
24 window.nativeClearTimeout(id);
25 timers.delete(id);
26};
In this setup, the clearAllTimeouts
function leverages the existing timers
Set to halt all the active timers. Since we've been diligent in tracking every new timer and removing each one that gets cleared or completed, this Set will always be current. As a result, clearAllTimeouts
becomes a powerful tool to halt all timers with a single call.