Waiting in JavaScript

Waiting in JavaScript: Why Code Can't Stop and Wait, Timers: setTimeout and setInterval, The Event Loop, in Pictures.

Updated

  1. Why Code Can't Stop and Wait (Apprentice): JavaScript runs one line at a time on one thread, so code that stands and waits freezes the whole page; asynchronous code starts a wait, carries on, and finishes the job later.
  2. Timers: setTimeout and setInterval (Apprentice): setTimeout runs a function once after a delay, setInterval runs it again and again, and clearTimeout and clearInterval cancel them with the ID each timer hands back.
  3. The Event Loop, in Pictures (Journeyman): The call stack runs one function at a time, finished timers wait their turn in the task queue, and the event loop moves the next one onto the stack only when the stack is empty, which is why setTimeout(fn, 0) runs after the code around it.