Skip to content

Instantly share code, notes, and snippets.

@hugocaillard
Last active August 29, 2015 14:27
Show Gist options
  • Save hugocaillard/af607b57d6fabcdee191 to your computer and use it in GitHub Desktop.
Save hugocaillard/af607b57d6fabcdee191 to your computer and use it in GitHub Desktop.
Pretty accurate ticker in JavaScript that runs code every # milliseconds
// Run code every # (here 200) milliseconds
function ticker() {
var now = 0;
var ticks = 0;
var delta = 0;
(function tick() {
now = Date.now();
ticks++;
console.log(ticks);
/*
Code that can take quite a long time
If it takes 200ms or more, the delta will be <= 0
The next tick will be called without delay
*/
delta = 200-(Date.now()-now)
setTimeout(tick, delta);
})();
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment