开发者

Sleep in JQuery?

greetings all i want to make JQuery sleep/wait for a second between two fu开发者_JS百科nctions

$('#div1').hide();
//sleep or wait or for a sec 
$("#div2").show();

how to do so ?


For your specific function .show() isn't queued, but there's an easy trick to make it queued so you can use .delay(), like this:

$('#div1').hide();
$("#div2").delay(1000).show(0);

By giving it a 0 duration argument, it's now an instant, but queued animation. Underneath this uses setTimeout(), so it's basically the same behavior as:

$('#div1').hide();
setTimeout(function() { $("#div2").show(); }, 1000);


Here ya go!

$('#div1').hide();
//sleep or wait or for a sec 
setTimeout('moomoo()', 1000);

function moomoo() {
  $("#div2").show();
}


The following should do what you want:

$("#div1").hide();
$("#div2").delay(1000).show(0);


You can't just pause the execution of the code between the calls. That would mean that the browser would not display the change caused by the hide call, as no updates are done while the code is running. The code would just appear to do nothing.

Use the setTimeout method to schedule code to be executed at a later time:

$('#div1').hide();
window.setTimeout(function(){
  $("#div2").show();
}, 1000);

This will set the element as hidden and schedule the code to show it to start later. The code will continue after the setTimeout call so that the function can exit and the browser gets back the control so that it can actually hide the element.


No real sleep, but this will achieve the same goal:

$('#div1').hide();
//sleep or wait or for a sec 
window.setTimeout(function() { $("#div2").show(); }, 1000);

Edit: well, I now stand corrected about "real" sleep, however using the setTimeout is still valid "pure JS" solution - your choice. :)

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜