Reputation: 1690
I'm trying to make a timer in JavaScript for animating in WebGL. This is the code that gets the elapsed time using the Date class.
var lastTime = Date.now();
var elapsed = 0;
var timeNow = Date.now();
function animate() {
timeNow = Date.now();
if(timeNow > lastTime) {
elapsed = timeNow - lastTime;
console.log(elapsed);
}
lastTime = timeNow;
}
Animate is called from a window.requestAnimationFrame() callback. But that seems to be generating a value between 16 and 17. It never goes above 20. Whats going on?
EDIT: Actually, that was my derp. Elapsed needed to be += not =. Thanks Abstract Algorithm for explaining why it was between 16 and 17. :)
Upvotes: 1
Views: 129
Reputation: 7771
You're calling animate
60 times per second, because that's probably what you set in requestAnimationFrame
(and is set by default). 1000 ms / 60 frames = 16.xx ms.
So animation is called every ~16ms and that's what you're getting.
if ( !window.requestAnimationFrame ) {
window.requestAnimationFrame = ( function() {
return window.webkitRequestAnimationFrame ||
window.mozRequestAnimationFrame ||
window.oRequestAnimationFrame ||
window.msRequestAnimationFrame ||
function( /* function FrameRequestCallback */ callback, /* DOMElement Element */ element ) {
window.setTimeout( callback, 1000 / 60 ); // so call it every ~16ms
};
} )();
}
Upvotes: 1