Is it true that if possible I should never use setInterval & setTimeout?

后端 未结 3 2019
花落未央
花落未央 2021-02-09 10:54

I am learning to code in JavaScript. I am programming something with some timed mouse animation. I\'m just about to add some code which draws the mouse path.

It\'s going

3条回答
  •  执笔经年
    2021-02-09 11:41

    Luz Caballero does a fair job of describing why rAF is a useful replacement for setInterval:

    https://dev.opera.com/articles/better-performance-with-requestanimationframe/.

    As for me, I now use rAF instead of setInterval because rAF has some built-in usefulness that would require additional coding with setInterval:

    • rAF will attempt to synchronize its calls with the display refresh cycle. This gives the code in the loop the "best chance" to complete between the refresh cycles.

    • If the tasks in loop#1 can't complete before loop#2 is requested, then the new loop#2 won't be called until the incomplete loop#1 is completed. This means the browser won't be overworked with a backlog of accumulated loops.

    • If the user switches to a different browser tab then loops in the current tab are suspended. This allows processing power to shift to the new tab instead of being used in the now invisible loop tap. This is also a power-saving feature on battery powered devices. If you want the loop to continue processing while a tab is unfocused you must use setInterval.

    • The rAF callback function automatically gets a high-precision timestamp argument. This allows rAF loops to calculate & use elapsed times. This elaped time can be used to (1) delay until a specified elapsed time has occurred or (2) "catch up" on time based tasks that were desired but were unable to be completed.

提交回复
热议问题