22

I mean calling multiple requestAnimationFrame with the same function in one time

function Draw() { /* DoSomething */ }
function AFunc() {
    /* prepare something */
    requestAnimationFrame(Draw);
}
function BFunc() {
    /* prepare something */
    requestAnimationFrame(Draw);
}

window.onload(function(){
   AFunc();
   BFunc();
});

What will happen? Will it duplicated? Would it be called 2 times in the same frame? Or it would be stacked and called on difference frame?

1 Answer 1

24

From the MDN documentation:

The callback method is passed a single argument, a DOMHighResTimeStamp, which indicates the current time when callbacks queued by requestAnimationFrame begin to fire. Multiple callbacks in a single frame, therefore, each receive the same timestamp even though time has passed during the computation of every previous callback's workload. This timestamp is a decimal number, in milliseconds, but with a minimal precision of 1ms (1000 µs).

(emphasis mine)

Also, from the spec:

When the requestAnimationFrame() method is called, the user agent must run the following steps:

...

  1. Append the method's argument to document's list of animation frame callbacks

and

When the user agent is to run the animation frame callbacks for a Document doc with a timestamp now, it must run the following steps:

...

  1. For each entry in callbacks, in order: invoke the callback

So for your question:

What will happen? Will it duplicated? Would it be called 2 times in the same frame? Or it would be stacked and called on difference frame?

The above all taken together shows that consecutive calls will be added to a list of callbacks, which will all be executed one after the other in the order they were added when the browser is due to run them, essentially duplicating the call to Draw in your code.

2
  • Thank you very much
    – Thaina Yu
    Jun 7, 2016 at 8:27
  • 1
    @Thaina, in your example, both request will be executed in the same frame despite the fact that the requests are for the same function. Had your example been different such that one request were sufficiently delayed, it would have been called on the next frame. There is nothing preventing you from requesting that the same function be executed twice or more in the same frame, i.e., duplicated. Dec 11, 2018 at 19:41

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.