DEV Community

Discussion on: JavaScript Closure Simply Explained

 
jaydeepkarena profile image
Jaydeep Karena

They print all at once because all setTimeout starts at same time and for all setTimeout 1 second passes at same time. What you want can be achieved by passing timeout values to 1000, 2000, 3000....

Following code will give you that output:

for(var i=0; i<5; i++) {
  setTimeout((function(index) {
    return function() {
      console.log(index);
    }
  }(i)), 1000 * i)
}