0

I'm trying to print out a number every 5 seconds:

for(i=0; i<10; i++) {
    setTimeout(function() {
        console.log(i)
    }, 5000 * i);
}

But instead I print 10 every 5 seconds because the loop finished and the global variable i is ten. Is there a way to avoid this happening?

Marty
  • 39,033
  • 19
  • 93
  • 162
Jakob Weisblat
  • 7,450
  • 9
  • 37
  • 65

3 Answers3

1

You can use bind to create a closure:

for (i = 0; i < 10; i++) {
    setTimeout((function(num) {
        console.log(num);
    }).bind(this, i), 5000 * i);
}
Marty
  • 39,033
  • 19
  • 93
  • 162
0

If ES6 Is allowed you could use a let declaration.

for (let i = 0; i < 10; i++) {
  setTimeout(function () {
      console.log(i)
  }, 5000 * i);
}
David Gomez
  • 2,762
  • 2
  • 18
  • 28
-1

The setTimeout function in javascript doesn't work like time.sleep(n) in python. The code will not pause and continue to run after 5s. It will set the body of the function in a queue that will be served in the time you picked. Since you loop 10 times, it will set all of your orders which are basically print i in a queue and serve them all together. To avoid this you can make a use of your loop in something that looks quite like this

setTimeout(function(){ console.log(i)}, 5000*i);

which will schedule each if the print 5s away from the last one !

Naing Lin Aung
  • 3,373
  • 4
  • 31
  • 48
Noctisdark
  • 350
  • 3
  • 17
  • 1
    The OP is already doing this, if you look closely at their code: `5000 * i`. This doesn't solve the issue with `i` though. – Felix Kling Nov 11 '15 at 05:50