Using setInterval with requestAnimationFrame Using setInterval with requestAnimationFrame google-chrome google-chrome

Using setInterval with requestAnimationFrame


The problem is that the browser is still only capable of doing one thing at a time. So, if it's rendering, it can't update the position.

When doing stuff to support variable framerates, you should always use Delta Timing. It works something like this:

requestAnimationFrame(function(e) {  document.getElementById('status').innerHTML = "Delta time: "+e;    // lag randomly  while(Math.random() > 0.0000001) {}    requestAnimationFrame(arguments.callee);});
<div id="status"></div>

As you can see (hopefully), regardless of framerate, the delta time shown goes up consistently. This means you can do, for example, angleFromStart = e/1000*Math.PI*2; and your dot will orbit at precisely 60 RPM.

var angle=0,    radian=Math.PI/180;var canvas=document.getElementById("canvas"),    context=canvas.getContext("2d");context.shadowColor="black";context.shadowBlur=100;requestAnimationFrame(function draw(e) {  angle = e/1000*Math.PI*2;    var x=canvas.width/2+Math.cos(angle)*canvas.width/4,        y=canvas.height/2+Math.sin(angle)*canvas.height/4;    context.clearRect(0, 0, canvas.width, canvas.height);    context.beginPath();    context.arc(x, y, 5, 0, Math.PI*2);    context.closePath();    for(var i=0; i<255; i++) {        context.fill();    }    requestAnimationFrame(draw);});
#canvas {    border: 1px solid black;}
<canvas id="canvas"></canvas>

PS: I love the new Stack Snippet feature!