-
Notifications
You must be signed in to change notification settings - Fork 0
/
setInterval-polyfill.js
56 lines (46 loc) · 1.12 KB
/
setInterval-polyfill.js
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
function createSetIntervalPolyfill() {
let intervalId = 0;
let intervalMap = {};
function setIntervalPolyfill(func, delay = 0, ...args) {
if (typeof func !== "function")
throw new TypeError('"callback" must be a function');
let uniqueId = intervalId++;
function repeat() {
intervalMap[uniqueId] = setTimeout(() => {
func(...args);
// terminating condition
if (intervalMap[uniqueId]) {
repeat();
}
}, delay);
}
repeat();
return uniqueId;
}
function clearIntervalPolyfill(intervalId) {
clearTimeout(intervalMap[intervalId]);
delete intervalMap[intervalId];
}
return {
setIntervalPolyfill,
clearIntervalPolyfill,
};
}
const {
setIntervalPolyfill,
clearIntervalPolyfill,
} = createSetIntervalPolyfill();
/* console.log(first(), second()) */
var counter = 0;
function greet(name) {
counter++;
console.log(`Hello ${name}`);
if (counter >= 3) {
clearIntervalPolyfill(intervalId);
}
}
const intervalId = setIntervalPolyfill(greet, 1000, "Shivam");
/*
setTimeout(()=>{
clearInterval(intervalId);
}, 3000) */