Answers:
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.
.removeClass('load')其他方式添加类的加载和完成,这可能是不希望的。如果您确实在等待异步操作完成,则最好的选择是在完成并成功后执行.addClass,否则请执行.addClass('error')一个想法
意识到这是一个老问题,但是我写了一个插件来解决这个问题,有人可能会觉得有用。
https://github.com/madbook/jquery.wait
让您执行以下操作:
$('#myElement').addClass('load').wait(2000).addClass('done');
有一个功能,但这是额外的: 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);
});
};
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>
使用setTimeout函数,例如访问此处