Forum Moderators: open

Message Too Old, No Replies

Running a simple function on a delayed loop

         

Jeremy_H

6:44 pm on Nov 6, 2006 (gmt 0)

10+ Year Member



Hello, I'm trying to create a function that will repeat itself a finite amount of times and after a specified delay.

Very simply, what I have is this:

for(i=1;i<3;i++){setTimeout(runMoreCode(i),2000);}
function runMoreCode(n){alert(n);}

To me, the above code should start after 2 seconds and alert the message "1", then, after another two seconds, it should alert with "2", and then the code ends.

What happens is the first "1" appears, but then I get an "Invalid argument error" on the page.

I can't seem to find the problem, any tips?

Thanks

Fotiman

7:15 pm on Nov 6, 2006 (gmt 0)

WebmasterWorld Senior Member 10+ Year Member Top Contributors Of The Month




To me, the above code should start after 2 seconds and alert the message "1", then, after another two seconds, it should alert with "2", and then the code ends.

No. Your loop does not wait 2 seconds between each call to setTimeout. So essentially what will happen is that it will call:

setTimeout(runMoreCode(1),2000);
setTimeout(runMoreCode(2),2000);

Note, these are in your for loop so will get executed one right after the other. The only delay added is a 2 second delay for BOTH calls. You probably should be using setInterval instead of setTimeout.

Also, you probably want to wrap your function call in quotes:

setTimeout("runMoreCode(" + i + ")",2000);

[edited by: Fotiman at 7:20 pm (utc) on Nov. 6, 2006]

Jeremy_H

1:34 am on Nov 7, 2006 (gmt 0)

10+ Year Member



Thank you very much for the reply,

So right now, I've changed my code to the following:

for(i=1;i<3;i++){setInterval("alert("+i+")",2000);}

What now happens is 2 seconds after the page loads, the function (alert message) runs twice, one right after each other. Then two seconds after the function runs twice again, continuous...

I'm now understanding that I'm calling the setInterval function twice, one right after each other (and not 2 seconds apart), but I don't know how to fix it.

How would I be able to call function to repeat itself after itself? Would I call a function once (that has some kind of counter), and at the end of the one function, to recall itself again after a delay? Once to counter reaches a set number, then it stops calling itself? I'll have to run some tests.

I'm curious why I should change the timeout to intraval. Right now the function keeps repeating every two seconds continuously. Am I skipping something?

Thanks.

daveVk

6:36 am on Nov 7, 2006 (gmt 0)

WebmasterWorld Senior Member 10+ Year Member



for(i=1;i<3;i++){setTimeout("alert("+i+")",2000*i);}

is one way to do it. This will set up 3 timers. If it is to repeat a large number of times then its probably more efficient to keep a count in a global variable and recall setTimeOut() in the function being called.