🟡 MediumEvent Loop Traps🐛 Debug Challenge

setTimeout inside a loop — all fire at once

Buggy Code — Can you spot the issue?

for (let i = 1; i <= 3; i++) {
  setTimeout(() => console.log(i), 1000);
}

Fixed Code

// Fix: multiply delay by iteration index
for (let i = 1; i <= 3; i++) {
  setTimeout(() => console.log(i), i * 1000);
}
// Logs: 1 at 1s, 2 at 2s, 3 at 3s

// Alternative: async/await with a sleep helper
const sleep = ms => new Promise(r => setTimeout(r, ms));

async function logSequentially() {
  for (let i = 1; i <= 3; i++) {
    await sleep(1000);
    console.log(i);
  }
}

Bug Explained

Bug: All three timeouts are scheduled at the same time with the same 1000ms delay. They all fire together after 1 second.

Explanation: Multiplying the delay (i * 1000) staggers the timers: 1000ms, 2000ms, 3000ms. The async/await version is cleaner and easier to read.

Key Insight: setTimeout delay is relative to when it's scheduled, not the previous timer. Stagger delays manually or use async/await with a sleep helper.

More Event Loop Traps Debug Challenges

🟡 MediumUI update blocked by sync code🔴 HardMicrotask starvation — UI never updates🔴 HardGenerator function called synchronously inside Promise🟡 MediumMixing microtasks and DOM updates

Practice spotting bugs live →

38 debug challenges with AI hints

🐛 Try Debug Lab