javascript 对 HTML 或文本设置使用延迟不起作用
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/3675935/
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
Using delay with HTML or text setting doesn't work
提问by NovumCoder
I have strange problem with the delay function here using the HTML function with it.
我在这里使用带有 HTML 函数的延迟函数有一个奇怪的问题。
I set an HTML text by using $( '#element').html( 'Hello World');
我通过使用设置了一个 HTML 文本 $( '#element').html( 'Hello World');
After setting the text I want to get this text disappear in 3 seconds.
设置文本后,我想让这个文本在 3 秒内消失。
So next line I wrote:
所以下一行我写道:
$('#element').delay( 3000).html( ' ');
This one doesn't work, it sets the HTML to  without waiting the 3 seconds, it looks like jQuery is skipping the delay function. Using this with fadeOut for example works fine. I guess this has something to do with this queue thing in delay.
这个不起作用,它将HTML设置为 不等待3秒,看起来jQuery正在跳过延迟功能。例如,将它与淡出一起使用效果很好。我想这与延迟队列的事情有关。
But why doesn't this work. Its a pretty simple, wait 3 seconds then run the HTML function.
但是为什么这不起作用。它非常简单,等待 3 秒然后运行 HTML 函数。
回答by Andy E
delay()defaults to the animation queue, for effects like fadeOut(), etc. You should use setTimeout()instead:
delay()默认为动画队列,用于fadeOut()等效果。您应该使用setTimeout()代替:
window.setTimeout(function () {
$("#element").html(' ');
}, 3000);
From http://api.jquery.com/delay/:
从http://api.jquery.com/delay/:
jQuery.delay() is best for delaying between queued jQuery effects and such, and is not a replacement for JavaScript's native setTimeoutfunction, which may be more appropriate for certain use cases.
jQuery.delay() 最适合在排队的 jQuery 效果等之间进行延迟,并且不能替代 JavaScript 的原生setTimeout函数,后者可能更适合某些用例。
回答by Nick Craver
.html()isn't a queued function. If you want it to happen in order in the animation queue, you'll have to .queue()it yourself, like this:
.html()不是排队功能。如果您希望它在动画队列中按顺序发生,则必须.queue()自己进行,如下所示:
$('#element').delay(3000).queue(function(n) {
$(this).html(' '); n();
});
If you're not chaining animations or anything like this, use setTimeout()or setInterval()(whichever is appropriate to the situation) directly, .delay()is just a wrapperfor setTimeout()and there's no reason to use extra code/complexity when there's no need.
如果你不将动画链接或类似的事情,使用setTimeout()或setInterval()直接(取适当的情况),.delay()是只是一个包装的setTimeout(),而且也没有理由使用额外的代码/复杂性时,有没有这个必要。

