Repository navigation
Expand file tree
/
Copy pathClearAllTimeout-and-ClearAllInterval.js
More file actions
84 lines (67 loc) · 2.04 KB
/
Copy pathClearAllTimeout-and-ClearAllInterval.js
File metadata and controls
84 lines (67 loc) · 2.04 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
/* 💡"JavaScript-with-JC"
👉 ClearAllTimeout and ClearAllInterval
💡ClearAllTimeout :-
setTimeout method returns a unique Id when it is invoked, which can be used to cancel the timer anytime using the clearTimeout method.
We can clear all the active timers by clearing all timeoutIds one by one using clearTimeout.
💡ClearAllInterval :-
setInterval method returns a unique Id when it is invoked, which can be used to cancel the interval anytime using the clearInterval method.
We can clear all the active intervals by clearing all intervalIds one by one using clearInterval.
*/
// 👉 1) Let's implement ClearAllTimeout()
let globalObject;
if (typeof window === "undefined") {
globalObject = global;
} else {
globalObject = window;
}
const timeoutIds = [];
const originalTimeout = globalObject.setTimeout;
globalObject.setTimeout = function (cbFn, delay) {
const timeoutId = originalTimeout(cbFn, delay);
timeoutIds.push(timeoutId);
return timeoutId;
};
globalObject.clearAllTimeout = function () {
while (timeoutIds.length) {
clearTimeout(timeoutIds.shift());
}
console.log("All above setTimeouts are cleared");
};
setTimeout(() => {
console.log("first");
}, 1000);
setTimeout(() => {
console.log("second");
}, 2000);
setTimeout(() => {
console.log("third");
}, 3000);
clearAllTimeout();
// 👇 output
// All above setTimeouts are cleared
// 👉 2) Let's implement ClearAllInterval()
const intervalIds = [];
const originalInterval = globalObject.setInterval;
globalObject.setInterval = function (cbFunc, delay) {
const intervalId = originalInterval(cbFunc, delay);
intervalIds.push(intervalId);
return intervalId;
};
globalObject.clearAllInterval = function () {
while (intervalIds.length) {
clearInterval(intervalIds.shift());
}
console.log("All above setIntervals are cleared");
};
setInterval(() => {
console.log("first");
}, 500);
setInterval(() => {
console.log("second");
}, 1000);
setInterval(() => {
console.log("third");
}, 2000);
clearAllInterval();
// 👇 output
// All above setIntervals are cleared