1

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?

Community
  • 1
  • 1
  • See: http://stackoverflow.com/questions/24849/is-there-some-way-to-introduce-a-delay-in-javascript and http://stackoverflow.com/questions/951021/javascript-sleep and http://stackoverflow.com/questions/1036612/how-to-make-a-sleep-in-javascript – Shog9 Feb 11 '10 at 02:05

2 Answers2

4

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.

Dominic Cooney
  • 5,736
  • 23
  • 37
0

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);
}
Nick Craver
  • 594,859
  • 130
  • 1,270
  • 1,139