This is my sample code:
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>
This output "1 3 4 6 7 8 9 15 all is done", all callback are called at the same time.
Someone can help me ?
thanks in advance
The problem is that each callback timeout is activated almost at the same time. You can do the following though:
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');
});
Using promises:
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');
});
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With