Good evening! Here's our prompt for today.
Mastering Time Control in Browsers with window.clearAllTimeouts
Imagine you have the power to control time in your browser. You can schedule events to happen in the future and even cancel them before they occur. This is exactly what window.setTimeout()
and window.clearTimeout()
allow you to do!
Scheduling a Future Event with setTimeout
Let's say you want to display a message that pops up after 5 seconds. You can do this by scheduling a function to run at a future time using window.setTimeout()
. Here's how it's done:
1const alertInFive = () => {
2 window.alert("This will show up after 5 seconds!");
3};
4
5const newTimeout = setTimeout(alertInFive, 5000);
Canceling a Scheduled Event with clearTimeout
What if you have second thoughts and decide you don't want that message to pop up? No worries, you can cancel the scheduled function using window.clearTimeout()
.
1const newTimeout = setTimeout(alertInFive, 5000);
2window.clearTimeout(newTimeout);
A New Challenge: Clearing All Timeouts
Now, let's level up. What if you have multiple functions scheduled and you want to cancel them all? Your mission, should you choose to accept it, is to create a function called window.clearAllTimeouts()
.
When invoked, this function will clear every timeout on the page. Here's what the usage would look like:
1setTimeout(func1, 500);
2setTimeout(func2, 500);
3setTimeout(func3, 500);
4setTimeout(func4, 500);
5
6window.clearAllTimeouts();
7// No scheduled functions run!

Your task is to write this utility function. It's like being a time-controlling superhero for your browser! Are you up for the challenge?
Try to solve this here or in Interactive Mode.
How do I practice this challenge?
xxxxxxxxxx
// Assuming window object in a Node.js environment for demonstration purposes.
global.window = {
timeouts: [],
setTimeout: function(callback, delay) {
const id = Math.random(); // Random ID for demonstration; usually, you'd use a more deterministic way
this.timeouts.push({ id, callback, delay });
return id;
},
clearTimeout: function(id) {
this.timeouts = this.timeouts.filter(timeout => timeout.id !== id);
},
clearAllTimeouts: function() {
// Your implementation goes here
},
// Utility method to emulate 'tick' of the event loop
_tick: function() {
this.timeouts.forEach(timeoutObj => timeoutObj.callback());
}
};
// Test cases for window.clearAllTimeouts
function runTests() {
let test1Flag = false;
let test2Flag = false;
// Schedule some timeouts
const timeout1 = window.setTimeout(() => { test1Flag = true; }, 1000);
const timeout2 = window.setTimeout(() => { test2Flag = true; }, 1000);
Here's our guided, illustrated walk-through.
How do I use this guide?