javascript – 使多个回调与jQuery $.when同步
作者:互联网
这是我的示例代码:
function out(msg)
{
$('#output').append(msg + '<br>');
}
var myDeferred = [];
$.each([8, 3, 4, 6, 9, 15, 7, 1], function (index, time)
{
myDeferred.push($.Deferred(function(dfd)
{
setTimeout(function ()
{
out(time);
dfd.resolve();
}, time * 1000);
}).promise());
});
$.when.apply($, myDeferred).then(function ()
{
out('all is done');
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="output"></div>
此输出“1 3 4 6 7 8 9 15全部完成”,同时调用所有回调.
但我希望“8 3 4 6 9 15 7 1全部完成”,所有回调都是一个接一个地调用.
有人可以帮帮我吗?
提前致谢
解决方法:
问题是每个回调超时几乎同时被激活.您可以执行以下操作:
function out(msg)
{
$('#output').append(msg + '<br>');
}
function foo(index, callback) {
var time = array[index];
out(time);
if (index == array.length - 1)
callback();
else
setTimeout(foo, time * 1000, index + 1, callback);
}
var array = [8, 3, 4, 6, 9, 15, 7, 1];
foo(0, function ()
{
out('all is done');
});
使用承诺:
function out(msg)
{
$('#output').append(msg + '<br>');
}
var myDeferred = [];
$.each([8, 3, 4, 6, 9, 15, 7, 1], function (index, time)
{
myDeferred.push($.Deferred(function(dfd)
{
var f = function() {
out(time);
dfd.resolve();
}
if (index > 0)
myDeferred[index - 1].done(function() { setTimeout(f, time * 1000); });
else
setTimeout(f, time * 1000);
}).promise());
});
$.when.apply($, myDeferred).then(function ()
{
out('all is done');
});
标签:javascript,jquery,asynchronous,synchronization,jquery-deferred 来源: https://codeday.me/bug/20190830/1765720.html