Belajar
← All lessons

How the JavaScript event loop works

Run four lines, one step at a time

Call stack
Microtasks
Task queue
Web APIs

script.js

console.log("A"); setTimeout(() => {  console.log("D");}, 0); Promise.resolve().then(() => {  console.log("C");}); console.log("B");

Guess the order then let your browser run it

SnippetBasicsawaitNestedTimers
Your guess

basics.js

console.log("A");setTimeout(() => console.log("B"), 0);Promise.resolve().then(() => console.log("C"));console.log("D");

A long loop freezes the page until it gives the loop a turn

Do 1.5 seconds of workOne long loopIn chunks
Frames painted 0
Clicks handled 0Longest wait 0 ms

work.js

button.onclick = () => clicks++; // one long loop: nothing else runs until it endsfunction work(ms) {  const end = performance.now() + ms;  while (performance.now() < end) {}} // in chunks: give the event loop a turn every 40 msasync function workInChunks(ms) {  const end = performance.now() + ms;  while (performance.now() < end) {    work(40);    await new Promise((r) => setTimeout(r));  }}

Topics

Next: How HTTPS works

Open lesson