AlgoDaily Solution
1const timers = new Set();
2window.nativeSetTimeout = window.setTimeout;
3window.nativeClearTimeout = window.clearTimeout;
4
5window.clearAllTimeouts = () => {
6 for (const id of timers) {
7 clearTimeout(id);
8 }
9};
10
11window.setTimeout = (cb, time, ...args) => {
12 const cbWrapper = () => {
13 cb(...args);
14 timers.delete(id);
15 };
16 const id = nativeSetTimeout(cbWrapper, time);
17 timers.add(id);
18 return id;
19};
20
21window.clearTimeout = (id) => {
22 nativeClearTimeout(id);
23 timers.delete(id);
24};Community Solutions
Community solutions are only available for premium users.
Access all course materials today
The rest of this tutorial's contents are only available for premium members. Please explore your options at the link below.
xxxxxxxxxx53
// 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.clearAllTimeoutsfunction runTests() { let test1Flag = false; let test2Flag = false; // Schedule some timeouts const timeout1 = window.setTimeout(() => { test1Flag = true; }, 1000);OUTPUT
Results will appear here.