Waiting function with deferreds

by Malin Jayakody

JavaScript

var loading;

var ready = function(callback) {
  var defer = $.Deferred();
  $.when(loading).done(callback.bind(this, defer));
  loading = defer.promise();
};

var asyncTest1 = function() {
  ready(function(defer) {
    setTimeout(function() {
      console.log('1');
      defer.resolve();
    }, 2000);
  });
};

var asyncTest2 = function() {
  ready(function(defer) {
    setTimeout(function() {
      console.log('2');
      defer.resolve();
    }, 1000);
  });
};


var asyncTest3 = function() {
  ready(function(defer) {
    setTimeout(function() {
      console.log('3');
      defer.resolve();
    }, 100);
  });
};

asyncTest1();
asyncTest2();
asyncTest3();