Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why does calling requestAnimationFrame at the beginning of a loop not cause infinite recursion?

What is going on that allows the rest of the loop to execute, and then for requestAnimationFrame to execute next frame?

I am misunderstanding how this method works, and can't see a clear explanation anywhere. I tried reading the timing specification here http://www.w3.org/TR/animation-timing/ but I couldn't make out how it worked.

For example, this code is taken from the threejs documentation.

var render = function () { 
  requestAnimationFrame(render); 
  cube.rotation.x += 0.1; 
  cube.rotation.y += 0.1;
  renderer.render(scene, camera); 
};
like image 663
dnv Avatar asked Feb 18 '14 21:02

dnv


People also ask

Can recursion causes infinite loop?

Iteration and recursion can occur infinitely: An infinite loop occurs with iteration if the loop-continuation test never becomes false; infinite recursion occurs if the recursion step does not reduce the problem in a manner that converges on the base case.

Is requestAnimationFrame recursive?

After the first render() call, RequestAnimationFrame will asynchronously take care of your render function calling it every ~60 times per second. Your function is not recursive, since Javascript will continue the code execution.

Why is requestAnimationFrame better than setInterval?

Another reason requestAnimationFrame is so useful is the fact that it gives you a time variable which you can use to calculate the amount of time between frames. This is not something that setInterval will do and since setInterval is not 100% accurate it is very possible your animation will get messed up over time.

What is the aim of the requestAnimationFrame method?

requestAnimationFrame() method tells the browser that you wish to perform an animation and requests that the browser calls a specified function to update an animation before the next repaint. The method takes a callback as an argument to be invoked before the repaint.


1 Answers

For the same reason that scheduling a callback with setTimeout in a loop wont cause infinite recursion, it schedules the next call on the JS event loop instead of executing it immediately.

The call is not made in the current context, so it's technically not recursion in the strict sense of the word, and it wont cause stack limit exceeded errors.

Event loop diagram
(source: dartlang.org)

This diagram is for Dart, but the concept is the same in JS. If you're interested in reading more about event loops, scheduling timers, and the difference between microtasks and macrotasks, check out this question.

like image 176
Nick Sweeting Avatar answered Oct 07 '22 14:10

Nick Sweeting