Skip to content

Commit

Permalink
Fixes #371
Browse files Browse the repository at this point in the history
  • Loading branch information
petkaantonov committed Oct 31, 2014
1 parent 023d9fd commit 70dc544
Show file tree
Hide file tree
Showing 2 changed files with 49 additions and 4 deletions.
23 changes: 20 additions & 3 deletions src/timers.js
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,7 @@ var _setTimeout = function(fn, ms) {
var arg0 = arguments[2];
var arg1 = arguments[3];
var arg2 = len >= 5 ? arguments[4] : void 0;
setTimeout(function() {
return setTimeout(function() {
fn(arg0, arg1, arg2);
}, ms|0);
};
Expand Down Expand Up @@ -59,14 +59,31 @@ Promise.prototype.delay = function Promise$delay(ms) {
return delay(this, ms);
};

function successClear(value) {
var handle = this;
// Deal with non-strict mode wrapping.
if (handle instanceof Number) handle = +handle;
clearTimeout(handle);
return value;
}

function failureClear(reason) {
var handle = this;
// Deal with non-strict mode wrapping.
if (handle instanceof Number) handle = +handle;
clearTimeout(handle);
throw reason;
}

Promise.prototype.timeout = function Promise$timeout(ms, message) {
ms = +ms;

var ret = new Promise(INTERNAL);
ret._propagateFrom(this, PROPAGATE_ALL);
ret._follow(this);
_setTimeout(afterTimeout, ms, ret, message, ms);
return ret.cancellable();
var handle = _setTimeout(afterTimeout, ms, ret, message, ms);
return ret.cancellable()
._then(successClear, failureClear, void 0, handle, void 0);
};

};
30 changes: 29 additions & 1 deletion test/mocha/timers.js
Original file line number Diff line number Diff line change
@@ -1,12 +1,12 @@
"use strict";
var assert = require("assert");

var adapter = require("../../js/debug/bluebird.js");
var fulfilled = adapter.fulfilled;
var rejected = adapter.rejected;
var pending = adapter.pending;
var Promise = adapter;
var Q = Promise;
var globalObject = new Function("return this;")();
/*
Copyright 2009–2012 Kristopher Michael Kowal. All rights reserved.
Permission is hereby granted, free of charge, to any person obtaining a copy
Expand Down Expand Up @@ -97,6 +97,34 @@ describe("timeout", function () {

doExpensiveOp().timeout(100);
});

it("should clear timeouts when success", function(done) {
var old = clearTimeout;
var handleSet = false;
clearTimeout = function(handle) {
handleSet = true;
globalObject.clearTimeout = old;
};

Q.delay(10).timeout(100).then(function() {
assert(handleSet);
done();
});
});

it("should clear timeouts when fail", function(done) {
var old = clearTimeout;
var handleSet = false;
clearTimeout = function(handle) {
handleSet = true;
globalObject.clearTimeout = old;
};

Q.delay(100).timeout(10).then(null, function() {
assert(handleSet);
done();
});
});
});

describe("delay", function () {
Expand Down

0 comments on commit 70dc544

Please sign in to comment.