简体   繁体   中英

requestAnimationFrame code execution time

Mozilla's docs on requestAnimationFrame states that the callback I pass to requestAnimationFrame will be ran before the next repaint.

I'm trying to figure out how to synchronize code with this.

Specifically, I want to:

  1. Apply a CSS class to an element
  2. Wait for that class to be completely processed and applied (executing any required layout / rendering / painting)
  3. Apply another CSS class to that same element

I want the above to execute as quickly as possible.

Can I use requestAnimationFrame to achieve this?

It seems if I wrap #1 with requestAnimationFrame, it could roll #1 and #3 into a single execution, then apply the paint. Same with wrapping #2 in RAF. Do I need to chain #3 in the callback of #1?

I've found one possible solution here, which is working, albeit a bit wonky.

If I chain all of these together in requestAnimationFrame callbacks, then it works as expected:

window.requestAnimationFrame(function()
  {
    // apply class 1
    window.requestAnimationFrame(function()
    {
      // apply class 2
    });
  });

I don't particularly like this solution, but it is a solution. Anything better out there?

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM