jQuery中的wait()或sleep()函数?


101

我想添加一个类,等待2秒钟,然后添加另一个类。

.addClass("load").wait(2sec).addClass("done");

有什么办法吗?

Answers:


186

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.

2
目前,这是一个较差的解决方案,因为它失去了对动画(如.stop())进行jquery控制的优势。一个更好的解决方案是.delay()
user151496 2015年

7
@ user123blahblah ...这是问题的正确解决方案(与动画无关)。.delay在动画队列之外执行千斤顶豆。谁支持您的错误评论,谁就会误导自己。
IncredibleHat

34

那会是.delay()

http://api.jquery.com/delay/

如果您正在做AJAX事情,您真的不应该只是自动编写“ done”,而应该真正等待响应,看看它是否真的完成了。


1
另外,史蒂文·史密斯(Steven)您想以.removeClass('load')其他方式添加类的加载和完成,这可能是不希望的。如果您确实在等待异步操作完成,则最好的选择是在完成并成功后执行.addClass,否则请执行.addClass('error')一个想法
Gary Green

52
jQUery的“ delay()”函数丝毫没有提供类似于通用“等待”功能的功能。它是动画系统的一部分,仅适用于动画队列。该函数始终立即返回,并且继续执行而不会暂停。
Pointy

22

delay()将无法完成工作。delay()的问题在于它是动画系统的一部分,并且仅适用于动画队列。

如果要在执行动画以外的内容之前要等待怎么办?

用这个:

window.setTimeout(function(){
                 // do whatever you want to do     
                  }, 600);

会发生什么?:在这种情况下,它在执行花括号内指定的代码之前要等待600毫秒。

一旦我弄清楚了对我的帮助很大,希望对您也有帮助!

重要说明:“ window.setTimeout”异步发生。编写代码时请记住这一点!



2

有一个功能,但这是额外的: http //docs.jquery.com/Cookbook/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);
    });
};

2

您可以使用该.delay()功能。
这是您所追求的:

.addClass("load").delay(2000).addClass("done");

0

xml4jQuery插件提供了sleep(ms,callback)方法。其余的链将在睡眠期后执行。

$(".toFill").html("Click here")
                .$on('click')
                .html('Loading...')
                .sleep(1000)
                .html( 'done')
                .toggleClass('clickable')
                .prepend('Still clickable <hr/>');
.toFill{border: dashed 2px palegreen; border-radius: 1em; display: inline-block;padding: 1em;}
        .clickable{ cursor: pointer; border-color: blue;}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
   <script type="text/javascript" src="https://cdn.xml4jquery.com/ajax/libs/xml4jquery/1.1.2/xml4jquery.js"></script>
        <div class="toFill clickable"></div>


By using our site, you acknowledge that you have read and understand our Cookie Policy and Privacy Policy.
Licensed under cc by-sa 3.0 with attribution required.