var counter = 0; function increase(){ var d = jQuery.Deferred(); var doIncrease = function() { if(counter < 10){ counter++; setTimeout(doIncrease, 1000); } else { d.resolve(); } }; doIncrease(); return d.promise(); }; increase().then(function() { alert(counter); });
请看这个例子,是在setTimeOut都执行完之后再alert(counter);