Explore Library
Code QuizAdvanced

Loop Variable Closure Bug

A classic var-in-a-loop closure mistake that logs the wrong values inside setTimeout.

Codejavascript
function scheduleTasks() {
  for (var i = 1; i <= 3; i++) {
    setTimeout(function () {
      console.log('Task ' + i);
    }, i * 100);
  }
}

scheduleTasks();
// Expected: Task 1, Task 2, Task 3

What is the bug that prevents this from logging Task 1, Task 2, Task 3?