gpt4 book ai didi

javascript - jQuery:在本地上下文中正确使用延迟(即没有 AJAX)

转载 作者:行者123 更新时间:2023-12-03 11:48:00 25 4
gpt4 key购买 nike

对于我确定是转发的内容表示歉意;我确实广泛地寻找了我的问题的答案(我也理解)。

我正在尝试学习做的是任意链接函数,以便它们必须在下一个函数发生之前完成,据我所知,这就是 jQuery's deferred() 的目的。所以在下面的代码中,我想象应该发生的是:

  1. 执行延迟加载对象中包含的函数;之后
  2. then() 中包含的函数执行;之后
  3. done() 中包含的函数执行。

宇宙中的每个教程都在 $.when() 之后使用 $.ajax() 对象,如果只想控制执行顺序,则该对象毫无用处本地背景。

这是我一直在尝试的:

var preloadDone = false,
var testDone = false,

var load = $.deferred(function() {
//cacheImages() is a plugin, works fine
$("img.image-loader.preload").cacheImages();
preloadDone = true;
});

var loader = $.when(load)
.then(function() {
if (preloadDone) {
console.log("then called in sequence");
} else {
console.log("then called out of sequence"); // wrong order, every time
}
XBS.cache.cbDone = true;
}).done(function() {
if (XBS.cache.cbDone) {
console.log("even done was called in right sequence!"); // proper order, every time
} else {
console.log("done() wasn't called in order..");
}
});

load.resolve(); // nothing happens
// load(); also tried this; nothing happens

据我所知,这与 jQuery $.when() 中给出的示例相同文档。莉尔帮忙?

最佳答案

这里是一个演示,演示如何在每个函数完成后依次运行多个函数。这是通过使用异步函数来实现的。

演示(依次运行 3 个函数。我有警报(“开始 *”),即您想要放置您喜欢做的工作并在完成的函数中包含您要运行的下一个函数。)

http://jsfiddle.net/5xLbk91c/

//the Assync function. Pause is the time in miliseconds to pause between loops

var asyncFor = function(params) {

var defaults = {
total: 0,
limit: 1,
pause: 10,
context: this
},
options = $.extend(defaults, params),
def = $.Deferred(),
step = 0,
done = 0;

this.loop = function() {
if (done < options.total) {
step = 0;
for (; step < options.limit; step += 1, done += 1) {
def.notifyWith(options.context, [done]);
}
setTimeout.apply(this, [this.loop, options.pause]);
} else {
def.resolveWith(options.context);
}
};

setTimeout.apply(this, [this.loop, options.pause]);
return def;
};




function one() {

asyncFor({
total: 1, // run only once. If you want to loop then increase to desired total.
context: this
}).progress(function(step) {

alert("starting one")

}).done(function() {

alert("finished one")

two()

});

}

function two() {

asyncFor({
total: 1,
context: this
}).progress(function(step) {

alert("starting two")

}).done(function() {

alert("finished two")

three()

});

}

function three() {

asyncFor({
total: 1,
context: this
}).progress(function(step) {

alert("starting three")

}).done(function() {

alert("finished three and all done")

});

}

关于javascript - jQuery:在本地上下文中正确使用延迟(即没有 AJAX),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25963390/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com