Tag Archives: async

Asynchronous loop with jQuery Deferred

On my previous experience with Flex I faced several times the necessity of delegate heavy loops to asynchronous processes; that was because either, the loop was too big or because each item required some heavy data or UI processing.

I was reading today about jQuery’s Deferred object (used mainly on $.when) and I decided to read more about it, understand it and use it when I required it. Deferred is a really simple but powerful object for some situations and one of those turns to be the asynchronous loops.

After some reading, brain overheat, and testing I came with this async loop that receive an options object with 4 properties:

  • total: The number of iterations. By default 0.
  • context: your this context to be sent to the callbacks. By default the loop this object.
  • limit: How many iterations before doing a pause. By default 100.
  • pause: A pause in milliseconds between each chunk. By default 10.

The more useful options are total and context. With those you can create an asynchronous loop that, upon each callback for each iteration will contain the proper this object.

var asyncFor = function(params) {
    var defaults = {
      total: 0,
      limit: 100,
      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;
  };

 

And a simple example on how to use it:

asyncFor({
  total: 10,
  context: this
}).progress(function(step) {
  console.log(step);
}).done(function() {
  console.log('complete!')
});

 

As a plus, a more complete example demonstrates the big difference while looping 10,000 times synchronously and asynchronously.