views:

10072

answers:

6

Hi. I want something like this in javascript.

for (i = 0; i < 10; i++) {
    alert(i);
    // now sleep 1 sec
    sleep(1000);
}

is there a built in Javascript or Jquery for this?

Thank you!

+5  A: 

use

setTimeout

method

rahul
Only that the setTimeout needs a continuation function as argument.
xtofl
I've tried using setTimeout, but I DO NOT need a continuation function .
Flueras Bogdan
A: 

Here is a good solution. But it involves java applet. http://www.devcheater.com/

Eldar Djafarov
And errrr, tie up your CPU?
Dominic Rodger
While it'll certainly pause the script that is just going to make the CPU work really hard to do nothing for a number of milliseconds. As a user I might be pissed that loading a page makes my one and only CPU go to 100% for 5 seconds.
Glen
+4  A: 

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.

xtofl
+2  A: 

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.

http://stackoverflow.com/questions/133310/how-can-i-get-jquery-to-perform-a-synchronous-rather-than-asynchronous-ajax-req

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.

Zoidberg
I've been doing callbacks with JS also, and the one thing I learned is that your loopFunc will be called with `this` everything but your `myObj`. You need to kinda store the required `this` in a closure.
xtofl
Apart from that, your suggestion to go event-based is worth a lot!
xtofl
The second example should work as the loopFunc will get executed within the myObj scope. So this should refer to myObj, the only issue that I don't like is that myObj has to be a globally available variable for setTimeout's execution to find it.Can you explain furthur what you mean by "this in a closure"?
Zoidberg
A: 

I have searched/googled quite a few webpages on javascript sleep/wait... and there is NO answer if you want javascript to "RUN, DELAY, RUN"... what most people got was either, "RUN, RUN(useless stuff), RUN" or "RUN, RUN + delayed RUN"....

So I ate some burgers and got thinking::: here is a solution that works... but you have to chop up your running codes...:::

//......................................... //example1:

<html>
<body>
<div id="id1">DISPLAY</div>

<script>
//javascript sleep by "therealdealsince1982"; copyrighted 2009
//setInterval
var i = 0;

function run() {
    //pieces of codes to run
    if (i==0){document.getElementById("id1").innerHTML= "<p>code segment "+ i +" is ran</p>"; }
    if (i==1){document.getElementById("id1").innerHTML= "<p>code segment "+ i +" is ran</p>"; }
    if (i==2){document.getElementById("id1").innerHTML= "<p>code segment "+ i +" is ran</p>"; }
    if (i >2){document.getElementById("id1").innerHTML= "<p>code segment "+ i +" is ran</p>"; }
    if (i==5){document.getElementById("id1").innerHTML= "<p>all code segment finished running</p>"; clearInterval(t); } //end interval, stops run
    i++; //segment of code finished running, next...
}

t=setInterval("run()",1000);

</script>
</body>
</html>

//.................................... //example2:

<html>
<body>
<div id="id1">DISPLAY</div>

<script>
//javascript sleep by "therealdealsince1982"; copyrighted 2009
//setTimeout
var i = 0;

function run() {
    //pieces of codes to run, can use switch statement
    if (i==0){document.getElementById("id1").innerHTML= "<p>code segment "+ i +" ran</p>"; sleep(1000);}
    if (i==1){document.getElementById("id1").innerHTML= "<p>code segment "+ i +" ran</p>"; sleep(2000);}
    if (i==2){document.getElementById("id1").innerHTML= "<p>code segment "+ i +" ran</p>"; sleep(3000);}
    if (i==3){document.getElementById("id1").innerHTML= "<p>code segment "+ i +" ran</p>";} //stops automatically
    i++;
}

function sleep(dur) {t=setTimeout("run()",dur);} //starts flow control again after dur

run(); //starts flow
</script>
</body>
</html>
+1  A: 

function sleep(delay) { var start = new Date().getTime(); while (new Date().getTime() < start + delay); }

abc
A standard CPU burner
Chris Noe