Ross
Ross

Reputation: 14415

One requestAnimationFrame invoked per redraw or multiple?

What happens when there are multiple requestAnimationFrame callbacks in relation to screen redraws?

With two requestAnimationFrame blocks i.e.

(function a() {
     requestAnimationFrame(a);
}())

(function b() {
     requestAnimationFrame(b);
}())

Will the sequence of execution be:

1:

 -> a
 -> b
 -> screen redrawn     
 -> a
 -> b
 -> screen redrawn
 ...

2:

 -> a
 -> screen redrawn   
 -> b
 -> screen redrawn     
 -> a
 -> screen redrawn
 ...

Upvotes: 2

Views: 148

Answers (1)

Palpatim
Palpatim

Reputation: 9262

That's an interesting question. Based on my read, a MozBeforePaint event should be fired for each registered callback before proceeding to the next frame. To test, I modified your code slightly (FIDDLE):

HTML

<button id="start">Start</button>
<button id="stop">Stop</button>

CSS

var aId, bId;

function a(ts) {
    console.log('a', ts);
    aId = requestAnimationFrame(a);
}

function b(ts) {
    console.log('b', ts);
    bId = requestAnimationFrame(b);
}

var startButton = document.getElementById('start');

var stopButton = document.getElementById('stop');

function stop() {
    window.cancelAnimationFrame(aId);
    window.cancelAnimationFrame(bId);
}

function start() {
    a();
    b();
}

startButton.addEventListener('click', start);
stopButton.addEventListener('click', stop);

The output after clicking start seems to confirm that expectation. The first invocation of a() and b() log undefined timestamps, because they're starting the animation directly rather than responding to a callback. Each subsequent invocation of a() logs a DOMHighResTimeStamp that matches the one logged by the invocation of b(), suggesting strongly that it's the same event firing both callbacks.

OUTPUT

a undefined
b undefined
a 123182.04999999944
b 123182.04999999944
a 123198.73199999893
b 123198.73199999893
a 123215.22000000004
b 123215.22000000004
a 123231.9179999995
b 123231.9179999995
a 123248.59099999958
b 123248.59099999958
a 123265.21899999898
b 123265.21899999898

Caveats:

  • I have no specific firsthand knowledge of the implementations; just my interpretation of the documentation and this test
  • This test was executed in Mac OS X Chrome 35; other browsers may produce different results

Upvotes: 3

Related Questions