Course contentsShow
← JavaScript
Lesson 1211 of 2,72327. The Event LoopFree lesson

Common setTimeout Pitfalls

Avoid issues like closure variable capture in loops and losing 'this' context in scheduled callbacks.

Common setTimeout Pitfalls

You'll learn: Two classic traps when using setTimeout — closure variable capture in loops and losing this context — and how to avoid them.

The Closure-in-Loop Problem

When you use setTimeout inside a loop with var, all the scheduled callbacks share the same variable reference. By the time they run, the loop has finished and the variable holds its final value:

for (var i = 0; i < 3; i++) {
  setTimeout(function() {
    console.log(i);  // Logs 3, 3, 3 — not 0, 1, 2!
  }, 100);
}

Why? All three callbacks "close over" the same i variable. When they finally execute (after 100ms), the loop is done and i equals 3.

Solution: Use let (block-scoped), or create a new scope with an IIFE, or pass i as a parameter:

for (let i = 0; i < 3; i++) {
  setTimeout(function() {
    console.log(i);  // Logs 0, 1, 2 correctly
  }, 100);
}

Losing this Context

When you pass a method to setTimeout, it loses its object context because the callback runs in a different execution context:

const user = {
  name: 'Alice',
  greet: function() {
    console.log(this.name);
  }
};

setTimeout(user.greet, 100);  // Logs undefined (or errors in strict mode)

Why? setTimeout calls your function without an object context — this becomes undefined or the global object.

Solution: Use an arrow function or bind:

setTimeout(() => user.greet(), 100);  // Works!
setTimeout(user.greet.bind(user), 100);  // Also works!

Key Takeaway: Always use let in loops with setTimeout to capture the correct loop variable, and wrap methods in arrow functions or use bind to preserve this context in callbacks.