Skip to content

Instantly share code, notes, and snippets.

@ZacharyL2
Created February 16, 2022 09:13
Show Gist options
  • Save ZacharyL2/615035573385ff34fa0ced148b543de6 to your computer and use it in GitHub Desktop.
Save ZacharyL2/615035573385ff34fa0ced148b543de6 to your computer and use it in GitHub Desktop.
A relatively accurate setInterval
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