One Pager Cheat Sheet
- With
window.setTimeout()
andwindow.clearTimeout()
, you can schedule and clear timeouts, respectively, but can you write a method,window.clearAllTimeouts
, to clear multiple timeouts at once? - We have overwritten the native
window.setTimeout
andwindow.clearTimeout
functions toadd
andremove
timer IDs to/from aSet
collection, in order to implement a customclearAllTimeouts
function. ClearAllTimeouts
iterates
througheach timer
andmanually clears
it.
This is our final solution.
To visualize the solution and step through the below code, click Visualize the Solution on the right-side menu or the VISUALIZE button in Interactive Mode.
xxxxxxxxxx
24
const timers = new Set();
window.nativeSetTimeout = window.setTimeout;
window.nativeClearTimeout = window.clearTimeout;
window.clearAllTimeouts = () => {
for (const id of timers) {
clearTimeout(id);
}
};
window.setTimeout = (cb, time, args) => {
const cbWrapper = () => {
cb(args);
timers.delete(id);
};
const id = nativeSetTimeout(cbWrapper, time);
timers.add(id);
return id;
};
window.clearTimeout = (id) => {
nativeClearTimeout(id);
timers.delete(id);
};
OUTPUT
:001 > Cmd/Ctrl-Enter to run, Cmd/Ctrl-/ to comment
Got more time? Let's keep going.
If you had any problems with this tutorial, check out the main forum thread here.