Is there an equivalent Javascript or Jquery sleep function?

拥有回忆 提交于 2019-12-01 17:27:49

问题


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!


回答1:


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.




回答2:


use

setTimeout

method




回答3:


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.




回答4:


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>



回答5:


I saw this comment "I've tried using setTimeout, but I DO NOT need a continuation function " and thought, yes, you do. What you don't need is a loop. You need a recursive function.

THIS

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

TRANSLATES TO THIS

function recursive( i, max )
{
    if ( i > max ) return;
    alert( i );
    i = i + 1;
    setTimeout( function(){ recursive(i, max); }, 1000 );
}

recursive(1, 10);

Example: http://jsfiddle.net/q76Qa/




回答6:


Well, if you have PHP installed on the webserver, you could use $.load or similar to call a PHP file that only has sleep(int) in it...




回答7:


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


来源:https://stackoverflow.com/questions/1277070/is-there-an-equivalent-javascript-or-jquery-sleep-function

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!