Last active
August 29, 2015 14:27
-
-
Save hugocaillard/af607b57d6fabcdee191 to your computer and use it in GitHub Desktop.
Pretty accurate ticker in JavaScript that runs code every # milliseconds
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
// 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