1 // Copyright Joyent, Inc. and other Node contributors.
3 // Permission is hereby granted, free of charge, to any person obtaining a
4 // copy of this software and associated documentation files (the
5 // "Software"), to deal in the Software without restriction, including
6 // without limitation the rights to use, copy, modify, merge, publish,
7 // distribute, sublicense, and/or sell copies of the Software, and to permit
8 // persons to whom the Software is furnished to do so, subject to the
9 // following conditions:
11 // The above copyright notice and this permission notice shall be included
12 // in all copies or substantial portions of the Software.
14 // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
15 // OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
16 // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN
17 // NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
18 // DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
19 // OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE
20 // USE OR OTHER DEALINGS IN THE SOFTWARE.
24 var Timer = process.binding('timer_wrap').Timer;
25 var L = require('_linklist');
26 var assert = require('assert').ok;
28 var kOnTimeout = Timer.kOnTimeout | 0;
30 // Timeout values > TIMEOUT_MAX are set to 1.
31 var TIMEOUT_MAX = 2147483647; // 2^31-1
33 var debug = require('util').debuglog('timer');
38 // Because often many sockets will have the same idle timeout we will not
39 // use one timeout watcher per item. It is too much overhead. Instead
40 // we'll use a single watcher for all sockets with the same timeout value
41 // and a linked list. This technique is described in the libev manual:
42 // http://pod.tst.eu/http://cvs.schmorp.de/libev/ev.pod#Be_smart_about_timeouts
44 // Object containing all lists, timers
45 // key = time in milliseconds
49 // the main function - creates lists on demand and the watchers associated
51 function insert(item, msecs) {
52 item._idleStart = Timer.now();
53 item._idleTimeout = msecs;
55 if (msecs < 0) return;
69 list[kOnTimeout] = listOnTimeout;
73 assert(!L.isEmpty(list)); // list is not empty
76 function listOnTimeout() {
77 var msecs = this.msecs;
80 debug('timeout callback %d', msecs);
82 var now = Timer.now();
83 debug('now: %s', now);
85 var diff, first, threw;
86 while (first = L.peek(list)) {
87 diff = now - first._idleStart;
89 list.start(msecs - diff, 0);
90 debug('%d list wait because diff is %d', msecs, diff);
94 assert(first !== L.peek(list));
96 if (!first._onTimeout) continue;
98 // v0.4 compatibility: if the timer callback throws and the
99 // domain or uncaughtException handler ignore the exception,
100 // other timers that expire on this tick should still run.
102 // https://github.com/joyent/node/issues/2631
103 var domain = first.domain;
104 if (domain && domain._disposed)
117 // We need to continue processing after domain error handling
118 // is complete, but not by using whatever domain was left over
119 // when the timeout threw its exception.
120 var oldDomain = process.domain;
121 process.domain = null;
122 process.nextTick(function() {
125 process.domain = oldDomain;
131 debug('%d list empty', msecs);
132 assert(L.isEmpty(list));
138 var unenroll = exports.unenroll = function(item) {
141 var list = lists[item._idleTimeout];
142 // if empty then stop the watcher
144 if (list && L.isEmpty(list)) {
145 debug('unenroll: list empty');
147 delete lists[item._idleTimeout];
149 // if active is called later, then we want to make sure not to insert again
150 item._idleTimeout = -1;
154 // Does not start the time, just sets up the members needed.
155 exports.enroll = function(item, msecs) {
156 // if this item was already in a list somewhere
157 // then we should unenroll it from that
158 if (item._idleNext) unenroll(item);
160 // Ensure that msecs fits into signed int32
161 if (msecs > 0x7fffffff) {
165 item._idleTimeout = msecs;
170 // call this whenever the item is active (not idle)
171 // it will reset its timeout.
172 exports.active = function(item) {
173 var msecs = item._idleTimeout;
175 var list = lists[msecs];
176 if (!list || L.isEmpty(list)) {
179 item._idleStart = Timer.now();
180 L.append(list, item);
191 exports.setTimeout = function(callback, after) {
194 after *= 1; // coalesce to number or NaN
196 if (!(after >= 1 && after <= TIMEOUT_MAX)) {
197 after = 1; // schedule on next tick, follows browser behaviour
200 timer = new Timeout(after);
202 if (arguments.length <= 2) {
203 timer._onTimeout = callback;
206 * Sometimes setTimeout is called with arguments, EG
208 * setTimeout(callback, 2000, "hello", "world")
210 * If that's the case we need to call the callback with
211 * those args. The overhead of an extra closure is not
212 * desired in the normal case.
214 var args = Array.prototype.slice.call(arguments, 2);
215 timer._onTimeout = function() {
216 callback.apply(timer, args);
220 if (process.domain) timer.domain = process.domain;
222 exports.active(timer);
228 exports.clearTimeout = function(timer) {
229 if (timer && (timer[kOnTimeout] || timer._onTimeout)) {
230 timer[kOnTimeout] = timer._onTimeout = null;
231 if (timer instanceof Timeout) {
232 timer.close(); // for after === 0
234 exports.unenroll(timer);
240 exports.setInterval = function(callback, repeat) {
241 repeat *= 1; // coalesce to number or NaN
243 if (!(repeat >= 1 && repeat <= TIMEOUT_MAX)) {
244 repeat = 1; // schedule on next tick, follows browser behaviour
247 var timer = new Timeout(repeat);
248 var args = Array.prototype.slice.call(arguments, 2);
249 timer._onTimeout = wrapper;
250 timer._repeat = true;
252 if (process.domain) timer.domain = process.domain;
253 exports.active(timer);
258 callback.apply(this, args);
259 // If callback called clearInterval().
260 if (timer._repeat === false) return;
261 // If timer is unref'd (or was - it's permanently removed from the list.)
263 this._handle.start(repeat, 0);
265 timer._idleTimeout = repeat;
266 exports.active(timer);
272 exports.clearInterval = function(timer) {
273 if (timer && timer._repeat) {
274 timer._repeat = false;
280 var Timeout = function(after) {
281 this._idleTimeout = after;
282 this._idlePrev = this;
283 this._idleNext = this;
284 this._idleStart = null;
285 this._onTimeout = null;
286 this._repeat = false;
289 Timeout.prototype.unref = function() {
291 this._handle.unref();
292 } else if (typeof(this._onTimeout) === 'function') {
293 var now = Timer.now();
294 if (!this._idleStart) this._idleStart = now;
295 var delay = this._idleStart + this._idleTimeout - now;
296 if (delay < 0) delay = 0;
297 exports.unenroll(this);
298 this._handle = new Timer();
299 this._handle[kOnTimeout] = this._onTimeout;
300 this._handle.start(delay, 0);
301 this._handle.domain = this.domain;
302 this._handle.unref();
306 Timeout.prototype.ref = function() {
311 Timeout.prototype.close = function() {
312 this._onTimeout = null;
314 this._handle[kOnTimeout] = null;
315 this._handle.close();
317 exports.unenroll(this);
322 var immediateQueue = {};
323 L.init(immediateQueue);
326 function processImmediate() {
327 var queue = immediateQueue;
328 var domain, immediate;
331 L.init(immediateQueue);
333 while (L.isEmpty(queue) === false) {
334 immediate = L.shift(queue);
335 domain = immediate.domain;
342 immediate._onImmediate();
346 if (!L.isEmpty(queue)) {
347 // Handle any remaining on next tick, assuming we're still
349 while (!L.isEmpty(immediateQueue)) {
350 L.append(queue, L.shift(immediateQueue));
352 immediateQueue = queue;
353 process.nextTick(processImmediate);
362 // Only round-trip to C++ land if we have to. Calling clearImmediate() on an
363 // immediate that's in |queue| is okay. Worst case is we make a superfluous
364 // call to NeedImmediateCallbackSetter().
365 if (L.isEmpty(immediateQueue)) {
366 process._needImmediateCallback = false;
371 function Immediate() { }
373 Immediate.prototype.domain = undefined;
374 Immediate.prototype._onImmediate = undefined;
375 Immediate.prototype._idleNext = undefined;
376 Immediate.prototype._idlePrev = undefined;
379 exports.setImmediate = function(callback) {
380 var immediate = new Immediate();
385 immediate._onImmediate = callback;
387 if (arguments.length > 1) {
389 for (index = 1; index < arguments.length; index++)
390 args.push(arguments[index]);
392 immediate._onImmediate = function() {
393 callback.apply(immediate, args);
397 if (!process._needImmediateCallback) {
398 process._needImmediateCallback = true;
399 process._immediateCallback = processImmediate;
403 immediate.domain = process.domain;
405 L.append(immediateQueue, immediate);
411 exports.clearImmediate = function(immediate) {
412 if (!immediate) return;
414 immediate._onImmediate = undefined;
418 if (L.isEmpty(immediateQueue)) {
419 process._needImmediateCallback = false;
424 // Internal APIs that need timeouts should use timers._unrefActive instead of
425 // timers.active as internal timeouts shouldn't hold the loop open
427 var unrefList, unrefTimer;
430 function unrefTimeout() {
431 var now = Timer.now();
433 debug('unrefTimer fired');
435 var diff, domain, first, threw;
436 while (first = L.peek(unrefList)) {
437 diff = now - first._idleStart;
439 if (diff < first._idleTimeout) {
440 diff = first._idleTimeout - diff;
441 unrefTimer.start(diff, 0);
442 unrefTimer.when = now + diff;
443 debug('unrefTimer rescheudling for later');
449 domain = first.domain;
451 if (!first._onTimeout) continue;
452 if (domain && domain._disposed) continue;
455 if (domain) domain.enter();
457 debug('unreftimer firing timeout');
463 if (threw) process.nextTick(unrefTimeout);
467 debug('unrefList is empty');
468 unrefTimer.when = -1;
472 exports._unrefActive = function(item) {
473 var msecs = item._idleTimeout;
474 if (!msecs || msecs < 0) return;
480 debug('unrefList initialized');
484 debug('unrefTimer initialized');
485 unrefTimer = new Timer();
487 unrefTimer.when = -1;
488 unrefTimer[kOnTimeout] = unrefTimeout;
491 var now = Timer.now();
492 item._idleStart = now;
494 if (L.isEmpty(unrefList)) {
495 debug('unrefList empty');
496 L.append(unrefList, item);
498 unrefTimer.start(msecs, 0);
499 unrefTimer.when = now + msecs;
500 debug('unrefTimer scheduled');
504 var when = now + msecs;
506 debug('unrefList find where we can insert');
510 for (cur = unrefList._idlePrev; cur != unrefList; cur = cur._idlePrev) {
511 them = cur._idleStart + cur._idleTimeout;
514 debug('unrefList inserting into middle of list');
518 if (unrefTimer.when > when) {
519 debug('unrefTimer is scheduled to fire too late, reschedule');
520 unrefTimer.start(msecs, 0);
521 unrefTimer.when = when;
528 debug('unrefList append to end');
529 L.append(unrefList, item);