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(){ ... })
?
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.
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.
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.
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.
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
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With