4

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.

Lakmal Caldera
  • 1,001
  • 2
  • 12
  • 25
  • 1
    It's used to call a function in a non-blocking fashion. So every function call after `setTimeout` is executed immediately while the `func` inside `setTimeout(func, 0)` is executed asynchroneously if and when there are resources available (kind of like a parallel, lower-priority thread). – pawel Nov 15 '14 at 01:04

1 Answers1

4

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.

Dean Ward
  • 4,793
  • 1
  • 29
  • 36