Skip to content

Commit

Permalink
Allow when/delay to be externally resolved
Browse files Browse the repository at this point in the history
- returns a full deferred instead of a promise
- clears the timeout when resolved/rejected
  • Loading branch information
scothis committed Aug 30, 2012
1 parent 98f8135 commit 8d17d48
Show file tree
Hide file tree
Showing 2 changed files with 22 additions and 4 deletions.
14 changes: 10 additions & 4 deletions delay.js
Expand Up @@ -16,7 +16,7 @@ define(['./when'], function(when) {
var undef;

/**
* Creates a new promise that will resolve after a msec delay. If promise
* Creates a new deferred that will resolve after a msec delay. If promise
* is supplied, the delay will start *after* the supplied promise is resolved.
*
* Usage:
Expand All @@ -39,13 +39,19 @@ define(['./when'], function(when) {
promise = undef;
}

var deferred = when.defer();
var deferred, timeout;

setTimeout(function() {
deferred = when.defer();
timeout = setTimeout(function() {
deferred.resolve(promise);
}, msec);

return deferred.promise;
deferred.promise.always(function () {
clearTimeout(timeout);
timeout = undef;
});

return deferred;
};

});
Expand Down
12 changes: 12 additions & 0 deletions test/delay.js
Expand Up @@ -59,6 +59,18 @@ buster.testCase('when/delay', {
assert.equals(val, 1);
}
).always(done);
},

'should clear timeout on reject': function(done) {
var d = delay(0);
d.reject(1);

d.then(
fail,
function(val) {
assert.equals(val, 1);
}
).always(done);
}
});
})(
Expand Down

0 comments on commit 8d17d48

Please sign in to comment.