Free Android CakePHP GMaps Articles by Bali Web Design

July 21, 2010

Sleep or wait process on javascript thread

Filed under: html,javascript — admin @ 10:10 pm

Actually there is no Thread.sleep method on javascript that work on Threading. Moreover there is no true threading in javascript. So everybody that want to deal with threading need to emulate it. In this article i would like to show you some method that emulate sleep method for waiting on a process. Each of this method has each own disadvantage, so you need to choose which is suitable for your case.

First method is sleep using javascript loop. This is first method that come to my mind when emulate sleep method on javascript. We wait for the process by checking the time in the loop.

function wait(millisecond) {
var date = new Date();
var current_date = null;

do { current_date = new Date(); }
while(current_date-date < millisecond)

// do something
wait(1000); // wait 1000 millisecond
// do something

The disadvantage is this method blocking the whole browser process. So you need to think if you want to wait process for long time.

Second method is only valid on Firefox windows. I got this function on this thread. This is work as a threading process. So it does not block your whole browser process.

* Netscape compatible WaitForDelay function.
* You can use it as an alternative to Thread.Sleep() in any major programming language
* that support it while JavaScript it self doesn't have any built-in function to do such a thing.
* parameters:
*  (Number) delay in millisecond
function nsWaitForDelay(delay) {
* Just uncomment this code if you're building an extention for Firefox.
* Since FF3, we'll have to ask for user permission to execute XPCOM objects.

// Get the current thread.
var thread = Components.classes[";1"].getService(Components.interfaces.nsIThreadManager).currentThread;

// Create an inner property to be used later as a notifier.
this.delayed = true;

/* Call JavaScript setTimeout function
* to execute this.delayed = false
* after it finish.
setTimeout("this.delayed = false;", delay);

* Keep looping until this.delayed = false
while (this.delayed) {
* This code will not freeze your browser as it's documented in here:

Third method is asynchronous method, so it will not blocking the whole browser process.

function my_method() {

you may also need to explore about setInterval and clearTimeout method for better use

No Comments »

No comments yet.

RSS feed for comments on this post. TrackBack URL

Leave a comment