Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

seTtimeout with zero seconds [duplicate]

This question is regarding setTimeout method in JavaScript. Is there some kind of benefit to calling another function inside a setTimeout after zero seconds? Like so,

 setTimeout(func, 0);

The reason why i'm asking is because I have noticed similar lines of code in certain plugin/libraries(for example, checkout offloadFn function in swipejs). Is it to support some kind of browser incompatibility or is it just bad way to write code and I should totally ignore it? I would love to know if there is some kind of benefit. Thank you for your time in advance.

like image 662
Lakmal Caldera Avatar asked Oct 26 '25 03:10

Lakmal Caldera


1 Answers

JavaScript is single-threaded so it can only do one thing at a time. When calling setTimeout with 0ms timeout you are telling the engine to schedule execution of that func as soon as it can. This will generally be after your current call stack has completed execution.

It's effectively a way of scheduling work to execute asynchronously.

See here for further details.

like image 190
Dean Ward Avatar answered Oct 28 '25 15:10

Dean Ward



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!