Skip to content

Instantly share code, notes, and snippets.

@peheje
Last active January 3, 2023 16:29
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save peheje/84a858871788407ce76bc1548f713c9d to your computer and use it in GitHub Desktop.
Save peheje/84a858871788407ce76bc1548f713c9d to your computer and use it in GitHub Desktop.
Accurate interval
function AccurateInterval(intervalMs, callback) {
var repeat;
var expected;
var timer;
function step() {
var err = Date.now() - expected;
callback();
console.log("error was", err, "ms");
if (repeat) {
expected += intervalMs;
timer = setTimeout(step, Math.max(0, intervalMs - err));
}
}
return {
start: function () {
repeat = true;
expected = Date.now() + intervalMs;
timer = setTimeout(step, intervalMs);
},
stop: function () {
repeat = false;
clearTimeout(timer);
}
};
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment