ExceptionLimeCat
ExceptionLimeCat

Reputation: 6410

JS setTimeout Not Delaying

Alright guys, I'm trying to add numbers on my page every 1/4 second or so. So the change is visible to the user. I'm using setTimeout and all my calculations are occurring correctly but without any delay. Here's the code:

for(var i = 0; i < 10; i++)
{
  setTimeout(addNum(i),250);
}

I've also tried capturing the return value:

for(var i = 0; i < 10; i++)
{
  var t = setTimeout(addNum(i),250);
}

I've also tried using function syntax as part of the setTimeout params:

for(var i = 0; i < 10; i++)
{
  var t = setTimeout(function(){array[j].innerHTML + 1},250);
}

I've also tried putting code in a string & the function call in a string. I can't ever get it to delay. Help Please!

Upvotes: 1

Views: 834

Answers (3)

Nightfirecat
Nightfirecat

Reputation: 11610

Perhaps instead, since you're running the same method multiple times, you should use the setInterval method instead? Here's an example of how you might do that.

Upvotes: 0

Jesus Ramos
Jesus Ramos

Reputation: 23266

Try setTimeout("addNum(" + i + ")", 250); the reason its not working is because its evaluating the parameter and executing it and changing it to something like setTimeout(result of addNum(i), 250);

Upvotes: 0

davin
davin

Reputation: 45555

How about:

var i=0;
function adder() {
   if(i>=10) {return;}
   addNum(i++);
   setTimeout(adder,250);
}
adder();

When you did setTimeout(addNum(i),250); you executed the function straight away (function name followed by () will execute it right away and pass the return value to the timeout to be executed 1/4 second later). So in a loop that would just execute all 10 immediately. Which is what you saw.

Capturing the return value var t = setTimeout(...); is helpful, but not in your use case; the value is the timer id number, used for cancelling the timeout.

Not sure what your last attempt is, although presumably it's the function body of your addNum routine, so the same logic applies as above.

Upvotes: 3

Related Questions