努力了解方法顺序、setTimeout() 和回调。
我需要调用 Isotope method layout()一旦 setTimeout() 函数完成,否则布局关闭且元素重叠。
// <--- 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
我可以看到在 setTimoute() 完成之前调用了 layout() 是异步的,但是我想不出一个好的方法来解决这个问题而不使用另一个 setTimeout?
最佳答案
你应该能够用 jQuery promises 解决这个问题(没有双关语!):
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,这样您就可以在整个异步任务完成时同步其他事件。
关于javascript - 使用 jQuery Isotope 了解 setTimeout() 和回调,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28881256/