English Deutsch Français Italiano Español Português 繁體中文 Bahasa Indonesia Tiếng Việt ภาษาไทย
All categories

In javascript, I need to repeatedly do some long code with spedified time interval between.
I've tried
var t=setTimeout("the really long code",1000)
but it doesn't work.

2006-06-07 12:26:17 · 3 answers · asked by Anonymous in Computers & Internet Programming & Design

The first time, the statement has to be executed immediately when called, then after a second the statement is executed again, blahblahblah...

2006-06-07 12:30:18 · update #1

3 answers

If you want this code to execute every 1000ms, do not use setTimeout, which is primarily for delaying the execution of a function, and especially do not use it in a loop or use loops as timers, as this can destabilize the client's system with strange race conditions that the engine may not be prepared to handle.
For this type of execution, one uses setInterval and clearInterval instead. See http://developer.mozilla.org/en/docs/DOM:window.setInterval .

Your code is replaced by "var t = window.setInterval('the really long code', 1000);". You can stop the loop by calling window.clearInterval(t).

2006-06-07 13:01:20 · answer #1 · answered by Ron 6 · 5 0

Here's why it doesn't work:

setTimeout("the really long code",1000), is only invoked once - from there onwards the function executes and exits normally.

If you want this function to be invoked periodically, infinitely (or for an arbitrary amount of time), do the following modification.

for (true){ // add a number if you don't want an infinite loop.
setTimeout ("functionName()", 1000);
}

2006-06-07 19:40:14 · answer #2 · answered by dinuksw 3 · 0 0

I've had the same trouble with setTimeout. The only way I have found to delay is to put in a for loop that does nothing but loop about 2000 times. The drawback to this is that you have no way to tell how fast the client machine will finish the loop.

2006-06-07 19:31:37 · answer #3 · answered by crgrier 4 · 0 0

fedest.com, questions and answers