diff --git a/lib/util/timers.js b/lib/util/timers.js index 86fcd9cddeb..08b9ec2aacb 100644 --- a/lib/util/timers.js +++ b/lib/util/timers.js @@ -58,17 +58,31 @@ function onTick () { // Refresh the fastNow value to the current uptime of the process fastNow = performance.now() + /** + * The idx variable is used to iterate over the FastTimeouts array. + * Expired FastTimeouts will be removed from the array by being + * replaced with the last element in the array. Thus, the idx variable + * will only be incremented if the current element is not removed. + * @type {number} + */ let idx = 0 + + /** + * The len variable will contain the length of the FastTimeouts array + * and will be decremented when a FastTimeout is removed from the array. + * @type {number} + */ let len = FastTimeouts.length while (idx < len) { + /** + * @type {FastTimeout} + */ const timer = FastTimeouts[idx] if (timer.state === PENDING) { timer.state = fastNow + timer.delay - TICK_MS - } - - if (timer.state > 0 && fastNow >= timer.state) { + } else if (timer.state > 0 && fastNow >= timer.state) { timer.state = TO_BE_CLEARED timer.callback(timer.opaque) } @@ -113,6 +127,18 @@ function refreshTimeout () { class FastTimeout { [kFastTimeout] = true + /** + * If the state of the timer is a non-negative number, it represents the + * time in milliseconds when the timer should expire. Values equal or less + * than zero represent the following states: + * - NOT_IN_LIST: The timer is not in the list of active timers. + * - TO_BE_CLEARED: The timer is in the list of active timers but is marked + * to be cleared. + * - PENDING: The timer is in the list of active timers and is waiting for + * @type {number} + */ + state = NOT_IN_LIST + /** * @constructor * @param {Function} callback A function to be executed after the timer expires. @@ -124,12 +150,6 @@ class FastTimeout { this.delay = delay this.opaque = opaque - // -2 not in timer list - // -1 in timer list but inactive - // 0 in timer list waiting for time - // > 0 in timer list waiting for time to expire - this.state = NOT_IN_LIST - this.refresh() }