Possible Duplicates:
Sleep in Javascript
Is there some way to introduce a delay in javascript?
how to make a sleep in javascript?
It seems no sleep() function provided, can we make one?
Possible Duplicates:
Sleep in Javascript
Is there some way to introduce a delay in javascript?
how to make a sleep in javascript?
It seems no sleep() function provided, can we make one?
Javascript is synchronous, there's a single execution thread in all browsers except chrome I believe. So in short, no, it doesn't support multithreading. You can hoever, use setTimeout
to produce sleep()
like functionality. This for example would pulse every 5 seconds, you could call another function to continue, etc.
function test() {
alert("interval");
setTimeout(test, 5000);
}
JavaScript doesn't specify any features relating to threading, and when it is embedded in web browsers it does not support threads (although HTML5 workers are somewhat like threads.)
Blocking the main thread in a browser is not recommended, because the page will appear unresponsive to user input.
If you just want to delay execution of the rest of your program, use setTimeout
. If you have this function:
function f() {
// do some stuff
sleep(1000);
// more stuff
}
Split it into two parts. The second part continues with setTimeout
:
function f() {
// do some stuff
setTimeout(g, 1000);
}
function g() {
// more stuff
}
The only thing to be aware of is that if you have event handlers wired up, they could fire if the user interacts with the page between the time f
and g
run.