如何使用 jQuery 等待 5 秒?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/1836105/
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
How to wait 5 seconds with jQuery?
提问by Andrew
I'm trying to create an effect where the page loads, and after 5 seconds, the success message on the screen fades out, or slides up.
我正在尝试创建页面加载的效果,5 秒后,屏幕上的成功消息淡出或向上滑动。
How can I achieve this?
我怎样才能做到这一点?
回答by Alex Bagnolini
Built in javascript setTimeout.
内置 javascript setTimeout。
setTimeout(
function()
{
//do something special
}, 5000);
UPDATE: you want to wait since when the page has finished loading, so put that code inside your $(document).ready(...);
script.
更新:您想在页面加载完成后等待,因此将该代码放入您的$(document).ready(...);
脚本中。
UPDATE 2: jquery 1.4.0 introduced the .delay
method. Check it out. Note that .delay only works with the jQuery effects queues.
更新 2:jquery 1.4.0 引入了该.delay
方法。检查一下。请注意, .delay 仅适用于 jQuery 效果队列。
回答by Doug Neiner
Use a normal javascript timer:
使用普通的 javascript 计时器:
$(function(){
function show_popup(){
$("#message").slideUp();
};
window.setTimeout( show_popup, 5000 ); // 5 seconds
});
This will wait 5 seconds after the DOM is ready. If you want to wait until the page is actually loaded
you need to use this:
这将在 DOM 准备好后等待 5 秒。如果你想等到页面实际上是loaded
你需要使用这个:
$(window).load(function(){
function show_popup(){
$("#message").slideUp();
};
window.setTimeout( show_popup, 5000 ); // 5 seconds
})
EDIT:In answer to the OP's comment asking if there is a way to do it in jQuery and not use setTimeout
the answer is no. But if you wanted to make it more "jQueryish" you could wrap it like this:
编辑:回答 OP 的评论,询问是否有办法在 jQuery 中做到这一点而不使用setTimeout
答案是否定的。但是如果你想让它更“jQueryish”,你可以像这样包装它:
$.wait = function( callback, seconds){
return window.setTimeout( callback, seconds * 1000 );
}
You could then call it like this:
然后你可以这样称呼它:
$.wait( function(){ $("#message").slideUp() }, 5);
回答by Ian Clark
I ran across this question and I thought I'd provide an update on this topic. jQuery (v1.5+) includes a Deferred
model, which (despite not adhering to the Promises/Aspec until jQuery 3)is generally regarded as being a clearer way to approach many asynchronous problems. Implementing a $.wait()
method using this approach is particularly readable I believe:
我遇到了这个问题,我想我会提供关于这个主题的更新。jQuery (v1.5+) 包含一个Deferred
模型,该模型(尽管直到 jQuery 3 才遵守Promises/A规范)通常被认为是处理许多异步问题的更清晰的方法。$.wait()
我相信使用这种方法实现方法特别易读:
$.wait = function(ms) {
var defer = $.Deferred();
setTimeout(function() { defer.resolve(); }, ms);
return defer;
};
And here's how you can use it:
以下是如何使用它:
$.wait(5000).then(disco);
However if, after pausing, you only wish to perform actions on a single jQuery selection, then you shouldbe using jQuery's native .delay()
which I believe also uses Deferred's under the hood:
但是,如果在暂停后,您只想对单个 jQuery 选择执行操作,那么您应该使用 jQuery 的本机.delay()
,我相信它也在幕后使用了 Deferred:
$(".my-element").delay(5000).fadeIn();
回答by maudulus
setTimeout(function(){
},5000);
Place your code inside of the { }
将您的代码放在 { }
300 = 0.3 seconds
700 = 0.7 seconds
1000 = 1 second
2000= 2 seconds
2200 = 2.2 seconds
3500 = 3.5 seconds
10000 = 10 seconds
etc.
等等。
回答by Jo Hasenau
Have been using this one for a message overlay that can be closed immediately on click or it does an autoclose after 10 seconds.
一直将这个用于消息覆盖,可以在单击时立即关闭,或者在 10 秒后自动关闭。
button = $('.status-button a', whatever);
if(button.hasClass('close')) {
button.delay(10000).queue(function() {
$(this).click().dequeue();
});
}
回答by izilotti
The Underscore libraryalso provides a "delay" function:
该下划线库还提供了“延迟”功能:
_.delay(function(msg) { console.log(msg); }, 5000, 'Hello');
回答by BananaAcid
Based on Joey's answer, I came up with an intended (by jQuery, read about 'queue') solution.
基于乔伊的回答,我想出了一个预期的(通过 jQuery,阅读“队列”)解决方案。
It somewhat follows the jQuery.animate() syntax - allows to be chained with other fx functions, supports 'slow' and other jQuery.fx.speeds as well as being fully jQuery. And will be handled the same way as animations, if you stop those.
它有点遵循 jQuery.animate() 语法 - 允许与其他 fx 函数链接,支持 'slow' 和其他 jQuery.fx.speeds 以及完全 jQuery。如果您停止动画,它将以与动画相同的方式处理。
jsFiddle test ground with more usages (like showing off .stop()), can be found here.
更多用法的 jsFiddle 测试场(比如炫耀 .stop()),可以在这里找到。
the core of the solution is:
解决方案的核心是:
$('<queue/>')
.delay(100 /*ms*/)
.queue( (next) => { $('#result').text('done.'); next(); } );
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="result"></div>
the whole as a plugin, supporting usage of $.wait() and $(..).wait() :
整个作为一个插件,支持使用 $.wait() 和 $(..).wait() :
// add wait as $.wait() standalone and $(elem).wait() for animation chaining
(function($) {
$.wait = function(duration, completeCallback, target) {
$target = $(target || '<queue />');
return $target.delay(duration).queue(function(next){completeCallback && completeCallback.call($target); next();});
}
$.fn.wait = function(duration, completeCallback) {
return $.wait.call(this, duration, completeCallback, this);
};
})(jQuery);
//TEST
$(function() {
// stand alone
$.wait(1000, function() {
$('#result')
.append('...done');
});
// chained
$('#result')
.append('go...')
.wait('slow', function() {
$(this).append('after slow');
})
.css({color: 'green'});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="result"></div>
Note:since wait adds to the animation stack, $.css() is executed immediately - as it is supposed: expected jQuery behaviour.
注意:由于等待添加到动画堆栈, $.css() 立即执行 - 正如它所假设的:预期的 jQuery 行为。
回答by mak
$( "#foo" ).slideUp( 300 ).delay( 5000 ).fadeIn( 400 );
回答by desbest
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');