Wednesday, February 10, 2016

javascript: setTimeout 0

means the function will be executed 5 seconds later.

but what does it mean if the time is set to 0, like this
it means the function will be deferred and executed at the end of the call stack (the currently executing method).

In this video, it explains it.

Call Stack, web api, event loop, callback queue
In a method, setTimeout(func, 0) was executed.

  • It will be first pushed "setTimeout(func, 0)" into the stack. 
  • Then the web APIs timer is running. (this does not block the stack) 
  • Once the time is over, pushed the callback function into callback queue. 
  • Once the stack is empty, the event loop will pick on callback from the callback queue ad push it into the stack. 
  • Then the callback function is executed.
Click "Save+Run"

Also, the javascript engine tries to do the render job every 16 milliseconds if the call stack is empty.
The render job is higher priority than the callback queue.
But if you have a lot of callback in the queue, and each callback can take a long time. It slows down the rendering.

No comments:

Post a Comment