Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is there any case where setTimeout(.., 0) is better than requestAnimationFrame()?

I've been using setTimeout(function(){ ... }, 0) as a way to delay a function call by one tick.

Normally I've been using this method for when I am trying to directly manipulate the event loop to make sure things execute in certain order, and in most cases it has to do with UI.

And sometimes I could sense that "tick", especially when I'm using this to run some 3rd party JS library on an element.

But I recently discovered requestAnimationFrame. This pretty much achieve the same thing, but in more graceful way.

Now I'm curious, are there any cases where it's more beneficial to use the setTimeout(function(){ ... }, 0) over requestAnimationFrame(function(){ ... })?

like image 823
Vlad Avatar asked May 26 '17 21:05

Vlad


People also ask

What happens when setTimeout is 0?

Invoking setTimeout with a callback, and zero as the second argument will schedule the callback to be run asynchronously, after the shortest possible delay - which will be around 10ms when the tab has focus and the JavaScript thread of execution is not busy.

Why is requestAnimationFrame better than setInterval or setTimeout?

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.

How does a setTimeout differ from window requestAnimationFrame?

While setTimeout is executed in x milliseconds (technically, x + y milliseconds as I explained earlier in this post), requestAnimationFrame keeps staying in the list called animation frame request callback list. The more you create requestAnimationFrame, the more handlers will be in the list.

What is alternative to setTimeout?

The setInterval method has the same syntax as setTimeout : let timerId = setInterval(func|code, [delay], [arg1], [arg2], ...) All arguments have the same meaning. But unlike setTimeout it runs the function not only once, but regularly after the given interval of time.


1 Answers

Depends, some cases like animations requestAnimationFrame is better and some cases like realtime process I prefer setTimeout 0.

Why? Because requestAnimationFrame is like a setTimeout(func, 1000/60), so setTimeout 0 is faster.

But if you compare requestAnimationFrame vs setTimeout(func, 1000/60). The requestAnimationFrame will be more exact than setTimeout.

like image 196
jtwalters Avatar answered Sep 30 '22 21:09

jtwalters