Javascript 在 JQuery 中睡觉?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/4437600/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-23 12:24:52  来源:igfitidea点击:

Sleep in JQuery?

javascriptjquery

提问by Mahmoud Saleh

greetings all i want to make JQuery sleep/wait for a second between two functions

问候我想让 JQuery 在两个函数之间休眠/等待一秒钟

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

how to do so ?

怎么办?

回答by Nick Craver

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:

对于您的特定功能.show()未排队,但有一个简单的技巧可以使其排队,以便您可以使用.delay(),如下所示:

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

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

通过给它一个0持续时间参数,它现在是一个即时但排队的动画。在setTimeout()它下面使用,所以它的行为基本上与:

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

回答by Barrie Reader

Here ya go!

给你!

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

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

回答by Marcus Stade

The following should do what you want:

以下应该做你想做的:

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

回答by Guffa

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 hidecall, as no updates are done while the code is running. The code would just appear to do nothing.

您不能只是在调用之间暂停代码的执行。这意味着浏览器不会显示由hide调用引起的更改,因为在代码运行时不会进行任何更新。该代码似乎什么都不做。

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

使用该setTimeout方法来安排稍后执行的代码:

$('#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 setTimeoutcall so that the function can exit and the browser gets back the control so that it can actually hide the element.

这会将元素设置为隐藏并安排代码显示它稍后开始。代码将在setTimeout调用后继续,以便函数可以退出,浏览器取回控制权,以便它可以真正隐藏元素。

回答by Shadow Wizard is Ear For You

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. :)

编辑:好吧,我现在对“真正的”睡眠进行了纠正,但是使用 setTimeout 仍然是有效的“纯 JS”解决方案 - 您的选择。:)