Skip to content

Instantly share code, notes, and snippets.

@hikariyo
Created December 10, 2022 12:04
Show Gist options
  • Save hikariyo/7523f05e580208398485930279f5456e to your computer and use it in GitHub Desktop.
Save hikariyo/7523f05e580208398485930279f5456e to your computer and use it in GitHub Desktop.
Simulate setInterval by setTimeout in JavaScript
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