Using setInterval with requestAnimationFrame

I would like to use setInterval for valid steps in the program and requestAnimationFrame for rendering. I was impressed that this would be the perfect combination: the rendering speed will not slow down the actual progression, so a drop in frame rate will only affect the frame rate and is still in sync. However, I got drops in the setInterval function.

An example of what I mean, intentionally stuck with shadows: http://jsfiddle.net/Ltdz168m/

Reduce or increase the number of refills and you will see the difference

It would seem that requestAnimationFrame is not really a rendering solution for lag slowing JavaScript down. How then would I update the logical side of things, what can be done at a speed of 60 frames per second, without rendering interference? Are WebWorkers necessary?

+6
source share
1 answer

The problem is that the browser is still able to do only one thing at a time. Thus, if it is a rendering, it cannot update the position.

When you make material to support framerates variables, 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 the frame rate, the displayed delta time is constantly growing. This means that you can do, for example, angleFromStart = e/1000*Math.PI*2; , and your point will be in orbit with an accuracy of 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 like the new Stack Snippet feature!

+17
source

Source: https://habr.com/ru/post/975379/


All Articles