-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,397
  • 8
  • 29
  • 39
  • 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
  • 3,840
  • 22
  • 31
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
  • 11,944
  • 3
  • 36
  • 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
  • 2,970
  • 3
  • 21
  • 29
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!

jh3y
  • 1,377
  • 7
  • 9