Forum Moderators: open
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
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]
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.