试图让我了解方法排序,setTimeout()和回调。
setTimeout()函数完成后,我需要调用Isotope方法layout(),否则布局将关闭并且元素重叠。
// <--- CODE
this.timeout = 400;
this.update = function() {
window.setTimeout(function() {
$(".item.is-loading").each(function(index) {
var _time = 100 * index,
$this = $(this);
window.setTimeout(function() {
$this.removeClass("is-loading").find("img").css({
width: "100%",
height: "auto"
});
}, _time);
})
}, instance.timeout);
instance.feed.isotope("layout");
};
// ---> CODE
我可以看到layout()在setTimoute()完成之前就被调用了,因为它是异步的,但是如果不使用另一个setTimeout,我想不出一种解决该问题的好方法?
您应该可以使用jQuery Promise解决此问题(无双关语!):
this.update = function() {
// immediately create an array of deferred objects, one for
// each element in the list below
var defs = $(".item.is-loading").map(function() {
return $.Deferred();
}).get();
window.setTimeout(function() {
$(".item.is-loading").each(function(index) {
var _time = 100 * index,
$this = $(this);
window.setTimeout(function() {
$this.removeClass("is-loading").find("img").css({
width: "100%",
height: "auto"
});
defs[index].resolve(); // flag that this deferred task finished
}, _time);
})
}, instance.timeout);
// once they're all done, update the layout
return $.when.apply($, defs).then(function() {
instance.feed.isotope("layout");
});
};
defs
必须立即创建该数组,否则$.when
进一步的调用将无法进行。
当每个内部setTimeout
调用完成时,defs
“解析”中的各个条目,并且该$.when()
调用确保仅当它们全部解析后,布局才会更新。
此外,update
函数本身现在还返回了一个Promise,因此您可以在整个异步任务完成时同步其他事件。
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句