Skip to content

Commit cd6122e

Browse files
tjfontainepiscisaureus
authored andcommitted
add ref/unref to setTimeout timers
1 parent 2637b5c commit cd6122e

File tree

1 file changed

+37
-5
lines changed

1 file changed

+37
-5
lines changed

lib/timers.js

Lines changed: 37 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -47,7 +47,6 @@ if (process.env.NODE_DEBUG && /timer/.test(process.env.NODE_DEBUG)) {
4747
// value = list
4848
var lists = {};
4949

50-
5150
// the main function - creates lists on demand and the watchers associated
5251
// with them.
5352
function insert(item, msecs) {
@@ -151,6 +150,7 @@ exports.enroll = function(item, msecs) {
151150
exports.active = function(item) {
152151
var msecs = item._idleTimeout;
153152
if (msecs >= 0) {
153+
154154
var list = lists[msecs];
155155
if (!list || L.isEmpty(list)) {
156156
insert(item, msecs);
@@ -176,9 +176,7 @@ exports.setTimeout = function(callback, after) {
176176
after = 1; // schedule on next tick, follows browser behaviour
177177
}
178178

179-
timer = { _idleTimeout: after };
180-
timer._idlePrev = timer;
181-
timer._idleNext = timer;
179+
timer = new Timeout(after);
182180

183181
if (arguments.length <= 2) {
184182
timer._onTimeout = callback;
@@ -209,7 +207,7 @@ exports.setTimeout = function(callback, after) {
209207
exports.clearTimeout = function(timer) {
210208
if (timer && (timer.ontimeout || timer._onTimeout)) {
211209
timer.ontimeout = timer._onTimeout = null;
212-
if (timer instanceof Timer) {
210+
if (timer instanceof Timer || timer instanceof Timeout) {
213211
timer.close(); // for after === 0
214212
} else {
215213
exports.unenroll(timer);
@@ -245,3 +243,37 @@ exports.clearInterval = function(timer) {
245243
timer.close();
246244
}
247245
};
246+
247+
var Timeout = function(after) {
248+
this._idleTimeout = after;
249+
this._idlePrev = this;
250+
this._idleNext = this;
251+
this._when = Date.now() + after;
252+
};
253+
254+
Timeout.prototype.unref = function() {
255+
if (!this._handle) {
256+
exports.unenroll(this);
257+
this._handle = new Timer();
258+
this._handle.ontimeout = this._onTimeout;
259+
this._handle.start(this._when - Date.now(), 0);
260+
this._handle.unref();
261+
} else {
262+
this._handle.unref();
263+
}
264+
};
265+
266+
Timeout.prototype.ref = function() {
267+
if (this._handle)
268+
this._handle.ref();
269+
};
270+
271+
Timeout.prototype.close = function() {
272+
this._onTimeout = null;
273+
if (this._handle) {
274+
this._handle.ontimeout = null;
275+
this._handle.close();
276+
} else {
277+
exports.unenroll(this);
278+
}
279+
};

0 commit comments

Comments
 (0)