Possiamo sincronizzare i task in jQuery usando i Deferred Object.
Abbiamo un timer che incrementa un valore e un altro che lo decrementa. Vogliamo fare in modo che il secondo timer parta quando il primo ha completato la sua routine. Ecco la soluzione:
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 );