Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Making multi callback synchronized with jQuery $.when

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.

But I want "8 3 4 6 9 15 7 1 all is done", all callback are called one after the other.

Someone can help me ?

thanks in advance

like image 884
dtcSearch Avatar asked Dec 30 '25 15:12

dtcSearch


1 Answers

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');
});
like image 127
JuniorCompressor Avatar answered Jan 01 '26 03:01

JuniorCompressor



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!