Is there an equivalent Javascript or Jquery sleep function?

use

setTimeout

method


There's no such thing, directly. You would have to tell javascript to wake 'something' up after some time using setTimeout.

This 'something' would be the code that you plan to execute after the sleep, of course.

From an example I found on the internet:

function dothingswithsleep( part ) {
    if( part == 0 ) {
        alert( "before sleep" );
        setTimeout( function() { dothingswithsleep( 1 ); }, 1000 );
    } else if( part == 1 ) {
        alert( "after sleep" );
    }
}

But that's fragile design. You better rethink your business logic to really do something after a second: call a different function instead of using these contrived helper variables.


First question, why do you want to sleep within a loop? If this is required, perhaps an event system should be put in place. I myself have tried the sleep tactic many times for mutli-threaded javascript programming and found it to not work well. The best way to do multi-threading in javascript is to use an event system such as that provided by YUI or almost any other framework. Have your listener subscribe to this event and do something whenever it occurs. IN these event frameworks you have full control of when your own custom event fires so their no big deal.

Here is the link for the YUI's event framework.

http://developer.yahoo.com/yui/examples/event/index.html

Here is how it might be coded using YUI

var myEvent = new YAHOO.util.CustomEvent('fooEvent');
// subscribe a function to be called (first param) inside the scope of an object
// (second param).
myEvent.subscribe(function() {alert(this.count++);},{count:0},true);
setTimeout('myEvent.fire()',1000);

That way of doing it is much cleaner and more compact. Or if you don't want to use an event framework try this

var myObj = {
    count:0,
    doSomething:function(){alert(this.count++);}
    loopFunc:function(){
        this.doSomething();
        setTimeout('myObj.loopFunc()',1000);
    }
}

That offers what you need, and its more compact.

But if you REALLY must have a sleep function in your code, then I would recommend making an synchronous ajax call to a simple serverside script. Then you can use the code on the server to sleep if you'd like. Below is a link to a question posted here that shows you how to make a synchronous call.

How can I get jQuery to perform a synchronous, rather than asynchronous, Ajax request?

But I highly recommend you go for the setTimeout way. Much cleaner, and you probably don't want to make any serverside calls if you can avoid it.