Created
February 16, 2022 09:13
-
-
Save ZacharyL2/615035573385ff34fa0ced148b543de6 to your computer and use it in GitHub Desktop.
A relatively accurate setInterval
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
function intervalTimer(callback, interval = 500) { | |
let counter = 1; | |
let timeoutId; | |
const startTime = Date.now(); | |
function main() { | |
const nowTime = Date.now(); | |
const nextTime = startTime + counter * interval; | |
timeoutId = setTimeout(main, interval - (nowTime - nextTime)); | |
console.log('deviation', nowTime - nextTime); | |
counter += 1; | |
callback(); | |
} | |
timeoutId = setTimeout(main, interval); | |
return () => { | |
clearTimeout(timeoutId); | |
}; | |
} | |
let value = 10; | |
const cancelTimer = intervalTimer(() => { | |
if (value > 0) { | |
value -= 1; | |
} else { | |
cancelTimer(); | |
} | |
}, 1000); | |
// deviation 3 | |
// deviation 1 | |
// deviation 0 | |
// deviation 2 |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment