jQuery: syncing timers with Deferred Objects

jQuery: syncing timers with Deferred Objects

Syncing JavaScript timers is a task that jQuery can handle through Deferred Objects.

Syncing JavaScript timers is a task that jQuery can handle through Deferred Objects.

We have two separate timers that increment and decrement a value, respectively. We want to sync those timers. Here's the solution:


var $counter = $( "#counter" );
var count = 0;

$counter.text( count );

var inc = function() {
    var def = $.Deferred();
    var timer = setInterval(function() {
      count++;
      $counter.text( count );
      if( count === 5 ) {
         clearInterval( timer );
         def.resolve();
      }
    }, 1000);
  return def.promise();
};

var dec = function() {
    var timer = setInterval(function() {
      count--;
      $counter.text( count );
      if( count === 0 ) {
         clearInterval( timer );
      }
    }, 1000);
};

inc().then( dec );

Demo

jQuery: syncing timers with Deferred objects