I'm trying to implement a game loop at runs every 10ms on both node.js and in modern web browsers. This version runs fine in Chrome (stays within 1ms accuracy):
var nextUpdate = Date.now();
function loop() {
console.log(Date.now());
// update() here
nextUpdate += 10; // ms
setTimeout(loop, Math.max(0, nextUpdate - Date.now()));
}
loop();
However, setTimeout is much less accurate in Firefox and node.js. Even a 0ms timeout takes longer than 10ms on average to execute, which causes the loop to go out of sync completely.
What is a better way to implement an accurate, cross-platform game loop in javascript?
Modern browsers support high precision timers with the Performance API.
Look at these links:
https://developer.mozilla.org/en-US/docs/Web/API/Performance