for (let i = 1; i <= 3; i++) {
setTimeout(() => console.log(i), 1000);
}// 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: 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.