nodejs/lib/timers.js

275 lines
7.1 KiB
JavaScript
Raw Permalink Normal View History

// Copyright Joyent, Inc. and other Node contributors.
//
// Permission is hereby granted, free of charge, to any person obtaining a
// copy of this software and associated documentation files (the
// "Software"), to deal in the Software without restriction, including
// without limitation the rights to use, copy, modify, merge, publish,
// distribute, sublicense, and/or sell copies of the Software, and to permit
// persons to whom the Software is furnished to do so, subject to the
// following conditions:
//
// The above copyright notice and this permission notice shall be included
// in all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN
// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE
// USE OR OTHER DEALINGS IN THE SOFTWARE.
'use strict';
const {
MathTrunc,
ObjectDefineProperties,
ObjectDefineProperty,
SymbolDispose,
SymbolToPrimitive,
} = primordials;
const binding = internalBinding('timers');
const {
immediateInfo,
} = binding;
const L = require('internal/linkedlist');
const {
async_id_symbol,
Timeout,
Immediate,
decRefCount,
immediateInfoFields: {
kCount,
kRefCount,
},
kRefed,
kHasPrimitive,
timerListMap,
timerListQueue,
immediateQueue,
insert,
knownTimersById,
} = require('internal/timers');
const {
promisify: { custom: customPromisify },
} = require('internal/util');
let debug = require('internal/util/debuglog').debuglog('timer', (fn) => {
debug = fn;
});
const { validateFunction } = require('internal/validators');
let timersPromises;
let timers;
const {
destroyHooksExist,
// The needed emit*() functions.
emitDestroy,
} = require('internal/async_hooks');
// Remove a timer. Cancels the timeout and resets the relevant timer properties.
function unenroll(item) {
if (item._destroyed)
return;
item._destroyed = true;
if (item[kHasPrimitive])
delete knownTimersById[item[async_id_symbol]];
// Fewer checks may be possible, but these cover everything.
if (destroyHooksExist() && item[async_id_symbol] !== undefined)
emitDestroy(item[async_id_symbol]);
L.remove(item);
// We only delete refed lists because unrefed ones are incredibly likely
// to come from http and be recreated shortly after.
// TODO: Long-term this could instead be handled by creating an internal
// clearTimeout that makes it clear that the list should not be deleted.
// That function could then be used by http and other similar modules.
if (item[kRefed]) {
// Compliment truncation during insert().
const msecs = MathTrunc(item._idleTimeout);
const list = timerListMap[msecs];
if (list !== undefined && L.isEmpty(list)) {
debug('unenroll: list empty');
timerListQueue.removeAt(list.priorityQueuePosition);
delete timerListMap[list.msecs];
}
decRefCount();
2010-10-26 11:56:32 -07:00
}
// If active is called later, then we want to make sure not to insert again
item._idleTimeout = -1;
}
2011-01-13 02:22:09 -08:00
/**
* Schedules the execution of a one-time `callback`
* after `after` milliseconds.
* @param {Function} callback
* @param {number} [after]
* @param {...any} [args]
* @returns {Timeout}
2010-10-26 12:52:31 -07:00
*/
function setTimeout(callback, after, ...args) {
validateFunction(callback, 'callback');
const timeout = new Timeout(callback, after, args.length ? args : undefined, false, true);
insert(timeout, timeout._idleTimeout);
return timeout;
}
ObjectDefineProperty(setTimeout, customPromisify, {
__proto__: null,
enumerable: true,
get() {
timersPromises ??= require('timers/promises');
return timersPromises.setTimeout;
},
});
/**
* Cancels a timeout.
* @param {Timeout | string | number} timer
* @returns {void}
*/
function clearTimeout(timer) {
if (timer?._onTimeout) {
timer._onTimeout = null;
unenroll(timer);
return;
}
if (typeof timer === 'number' || typeof timer === 'string') {
const timerInstance = knownTimersById[timer];
if (timerInstance !== undefined) {
timerInstance._onTimeout = null;
unenroll(timerInstance);
}
2010-10-29 00:00:43 -07:00
}
}
2010-10-26 12:52:31 -07:00
/**
* Schedules repeated execution of `callback`
* every `repeat` milliseconds.
* @param {Function} callback
* @param {number} [repeat]
* @param {...any} [args]
* @returns {Timeout}
*/
function setInterval(callback, repeat, ...args) {
validateFunction(callback, 'callback');
const timeout = new Timeout(callback, repeat, args.length ? args : undefined, true, true);
insert(timeout, timeout._idleTimeout);
return timeout;
}
/**
* Cancels an interval.
* @param {Timeout | string | number} timer
* @returns {void}
*/
function clearInterval(timer) {
// clearTimeout and clearInterval can be used to clear timers created from
// both setTimeout and setInterval, as specified by HTML Living Standard:
// https://html.spec.whatwg.org/multipage/timers-and-user-prompts.html#dom-setinterval
clearTimeout(timer);
}
2012-07-12 22:19:01 -04:00
Timeout.prototype.close = function() {
clearTimeout(this);
return this;
2012-07-12 22:19:01 -04:00
};
2012-08-07 22:12:01 -04:00
Timeout.prototype[SymbolDispose] = function() {
clearTimeout(this);
};
/**
* Coerces a `Timeout` to a primitive.
* @returns {number}
*/
Timeout.prototype[SymbolToPrimitive] = function() {
const id = this[async_id_symbol];
if (!this[kHasPrimitive]) {
this[kHasPrimitive] = true;
knownTimersById[id] = this;
}
return id;
};
/**
* Schedules the immediate execution of `callback`
* after I/O events' callbacks.
* @param {Function} callback
* @param {...any} [args]
* @returns {Immediate}
*/
function setImmediate(callback, ...args) {
validateFunction(callback, 'callback');
return new Immediate(callback, args.length ? args : undefined);
}
ObjectDefineProperty(setImmediate, customPromisify, {
__proto__: null,
enumerable: true,
get() {
timersPromises ??= require('timers/promises');
return timersPromises.setImmediate;
},
});
/**
* Cancels an immediate.
* @param {Immediate} immediate
* @returns {void}
*/
function clearImmediate(immediate) {
if (!immediate?._onImmediate || immediate._destroyed)
return;
2012-08-07 22:12:01 -04:00
immediateInfo[kCount]--;
immediate._destroyed = true;
timers: cross JS/C++ border less frequently This removes the `process._needImmediateCallback` property and its semantics of having a 1/0 switch that tells C++ whether immediates are currently scheduled. Instead, a counter keeping track of all immediates is created, that can be increased on `setImmediate()` or decreased when an immediate is run or cleared. This is faster, because rather than reading/writing a C++ getter, this operation can be performed as a direct memory read/write via a typed array. The only C++ call that is left to make is activating the native handles upon creation of the first `Immediate` after the queue is empty. One other (good!) side-effect is that `immediate._destroyed` now reliably tells whether an `immediate` is still scheduled to run or not. Also, as a nice extra, this should make it easier to implement an internal variant of `setImmediate` for C++ that piggybacks off the same mechanism, which should be useful at least for async hooks and HTTP/2. Benchmark results: $ ./node benchmark/compare.js --new ./node --old ./node-master-1b093cb93df0 --runs 10 --filter immediate timers | Rscript benchmark/compare.R [00:08:53|% 100| 4/4 files | 20/20 runs | 1/1 configs]: Done improvement confidence p.value timers/immediate.js type="breadth" thousands=2000 25.61 % ** 1.432301e-03 timers/immediate.js type="breadth1" thousands=2000 7.66 % 1.320233e-01 timers/immediate.js type="breadth4" thousands=2000 4.61 % 5.669053e-01 timers/immediate.js type="clear" thousands=2000 311.40 % *** 3.896291e-07 timers/immediate.js type="depth" thousands=2000 17.54 % ** 9.755389e-03 timers/immediate.js type="depth1" thousands=2000 17.09 % *** 7.176229e-04 timers/set-immediate-breadth-args.js millions=5 10.63 % * 4.250034e-02 timers/set-immediate-breadth.js millions=10 20.62 % *** 9.150439e-07 timers/set-immediate-depth-args.js millions=10 17.97 % *** 6.819135e-10 PR-URL: https://github.com/nodejs/node/pull/17064 Reviewed-By: Refael Ackermann <refack@gmail.com> Reviewed-By: Minwoo Jung <minwoo@nodesource.com> Reviewed-By: James M Snell <jasnell@gmail.com> Reviewed-By: Ben Noordhuis <info@bnoordhuis.nl>
2017-11-16 00:43:12 +01:00
if (immediate[kRefed] && --immediateInfo[kRefCount] === 0) {
// We need to use the binding as the receiver for fast API calls.
binding.toggleImmediateRef(false);
}
immediate[kRefed] = null;
if (destroyHooksExist() && immediate[async_id_symbol] !== undefined) {
emitDestroy(immediate[async_id_symbol]);
}
immediate._onImmediate = null;
2012-08-07 22:12:01 -04:00
immediateQueue.remove(immediate);
}
Immediate.prototype[SymbolDispose] = function() {
clearImmediate(this);
};
module.exports = timers = {
setTimeout,
clearTimeout,
setImmediate,
clearImmediate,
setInterval,
clearInterval,
2012-08-07 22:12:01 -04:00
};
ObjectDefineProperties(timers, {
promises: {
__proto__: null,
configurable: true,
enumerable: true,
get() {
timersPromises ??= require('timers/promises');
return timersPromises;
},
},
});