-2

I'm trying to run a setTimeout inside a for loop. I've followed recommendations to move the setTimeout into a separate function. However, everything seems to fire at once, at the end of the loop.

In this example, I'd like the console.logs to fire every second.

function setDelay(i) {
    setTimeout(function(){
        console.log(i);
    }, 1000);
}

for (var i = 1; i <= 10; ++i) {
    setDelay(i);
}
Sebastien
  • 2,607
  • 9
  • 30
  • 40
  • I'm quite curious about the output really, i guess the `i` variable retains the value because its in a different function? If it was the loop variable surely it would just output `10` ten times. – TJHeuvel Oct 05 '15 at 12:55
  • I'm just being curious: why do you ask a question and don't even bother answering people's comments and answers? – sbedulin Oct 29 '15 at 09:30

6 Answers6

1

The easiest way to achieve this is to multiply timeout by index:

function setDelay(i) {
    setTimeout(function(){
        console.log(i);
    }, i * 1000);
}
sbedulin
  • 4,102
  • 24
  • 34
0

The problem with your code is that it will create 10 timeouts that fire more or less simultaneously after 1 second.

If you want to execute something every second (or any other frequency), you can use setInterval instead.

boxjar
  • 69
  • 3
0

There is no delay in your loop, so what you actually want is to set an interval at 1000ms the first time and 2000ms the second etc.

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

for (var i = 1; i <= 10; ++i) {
    setDelay(i);
}

This can easily be achieved by multiplying the time by your index variable.

TJHeuvel
  • 12,403
  • 4
  • 37
  • 46
0

You could better use setInterval() instead of setTimeout(). With clearInterval() you can stop it from running. The code you made does not work because the for-loop doesn't have scope from itself. You can work around the for loop by using the setInterval().

Hiltje
  • 140
  • 1
  • 5
0

You can also do this:

(function updateEverySecond(){
    console.log(1);
    setTimeout(updateEverySecond, 1000);
})();
Sotiris Kiritsis
  • 3,178
  • 3
  • 23
  • 31
0

The use of setInterval and reference to a counter may be a better solution for you.

(function(){
  var count        = 0,
      upperBound   = 3,
      intervalTime = 1000,
      interval     = setInterval(function(){
        if (count === upperBound) {
         clearInterval(interval);
        } else {
          console.log(count);
          count++;
        }
      }, intervalTime);
}());

Hope that helps you out!

Jhey
  • 1,377
  • 7
  • 10