JavaScript Note: Thread & Event Loop

Event Loop

  • JavaScript only has one thread.
    1. No dead lock
    2. No thread switching
    3. Execution context stack
  • It uses Event Loop to achieve async or setTimeout
    1. It is a queue, called "task queue".

setTimeout(function(){console.log(1);}, 0);

Above example will always show 2, 1, because the callback of setTimeout will only be called from queue after main thread is done.

note: console.log in browser is actually async

Ref: Philip Roberts: What the heck is the event loop anyway? | JSConf EU