-
-
Save hikariyo/7523f05e580208398485930279f5456e to your computer and use it in GitHub Desktop.
Simulate setInterval by setTimeout in JavaScript
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
const interval = { | |
_active: new Set(), | |
_id: 0, | |
set(callback, delay) { | |
const id = this._id++ | |
this._active.add(id) | |
const handler = () => { | |
if (!this._active.has(id)) { | |
return | |
} | |
setTimeout(() => { | |
callback() | |
handler() | |
}, delay) | |
} | |
handler() | |
return id | |
}, | |
clear(id) { | |
this._active.delete(id) | |
} | |
} | |
let count = 0 | |
const id = interval.set(() => { | |
count++ | |
console.log(`count is ${count}`) | |
if (count === 5) { | |
interval.clear(id) | |
} | |
}, 500) | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment