jQuery jquery中的wait()或sleep()函数?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/5722791/
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
wait() or sleep() function in jquery?
提问by Steven Moss
I want to add a class, wait 2 seconds and add another class.
我想添加一个类,等待 2 秒钟,然后添加另一个类。
.addClass("load").wait(2sec).addClass("done");
Is there any way?
有什么办法吗?
回答by ctcherry
setTimeout will execute some code after a delay of some period of time (measured in milliseconds). However, an important note: because of the nature of javascript, the rest of the code continues to run after the timer is setup:
setTimeout 将在延迟一段时间(以毫秒为单位)后执行一些代码。但是,一个重要的注意事项:由于 javascript 的性质,其余代码在设置计时器后继续运行:
$('#someid').addClass("load");
setTimeout(function(){
$('#someid').addClass("done");
}, 2000);
// Any code here will execute immediately after the 'load' class is added to the element.
回答by Oscar Godson
That'd be .delay()
.
那就是.delay()
。
If you are doing AJAX stuff tho, you really shouldn't just auto write "done" you should really wait for a response and see if it's actually done.
如果你正在做 AJAX 的东西,你真的不应该只是自动写“完成”,你应该等待响应并看看它是否真的完成了。
回答by J. Louw
delay() will not do the job. The problem with delay() is it's part of the animation system, and only applies to animation queues.
delay() 不会完成这项工作。delay() 的问题在于它是动画系统的一部分,仅适用于动画队列。
What if you want to wait before executing something outside of animation??
如果你想在执行动画之外的东西之前等待怎么办??
Use this:
用这个:
window.setTimeout(function(){
// do whatever you want to do
}, 600);
What happens?: In this scenario it waits 600 miliseconds before executing the code specified within the curly braces.
会发生什么?:在这种情况下,它在执行大括号内指定的代码之前等待 600 毫秒。
This helped me a great deal once I figured it out and hope it will help you as well!
一旦我弄清楚了,这对我帮助很大,希望它也能帮助你!
回答by madlee
Realize that this is an old question, but I wrote a plugin to address this issue that someone might find useful.
意识到这是一个老问题,但我写了一个插件来解决这个问题,有人可能会觉得有用。
https://github.com/madbook/jquery.wait
https://github.com/madbook/jquery.wait
lets you do this:
让你这样做:
$('#myElement').addClass('load').wait(2000).addClass('done');
回答by mrzmyr
There is an function, but it's extra: http://docs.jquery.com/Cookbook/wait
有一个功能,但它是额外的:http: //docs.jquery.com/Cookbook/wait
This little snippet allows you to wait:
这个小片段让你等待:
$.fn.wait = function(time, type) {
time = time || 1000;
type = type || "fx";
return this.queue(type, function() {
var self = this;
setTimeout(function() {
$(self).dequeue();
}, time);
});
};
回答by The Web Developer Blog
You can use the .delay()
function.
This is what you're after:
您可以使用该.delay()
功能。
这就是你所追求的:
.addClass("load").delay(2000).addClass("done");
回答by Abhinav Ranjan Sinha
Using setTimeout function, for example Visit here for example
使用 setTimeout 函数,例如访问这里例如