Skip to content

Commit

Permalink
perf: fast timers
Browse files Browse the repository at this point in the history
  • Loading branch information
ronag committed Feb 4, 2023
1 parent 6b96f5a commit e0ffe52
Showing 1 changed file with 49 additions and 10 deletions.
59 changes: 49 additions & 10 deletions lib/client.js
Original file line number Diff line number Diff line change
Expand Up @@ -83,6 +83,46 @@ try {
channels.connected = { hasSubscribers: false }
}

let fastNow = Date.now()
const fastTimers = new Set()
const fastNowInterval = setInterval(() => {
fastNow = Date.now()
for (const timer of fastTimers) {
if (fastNow >= timer.expires) {
timer.expires = 0
timer.callback(timer.opaque)
}
}
}, 1e3)
if (fastNowInterval.unref) {
fastNowInterval.unref()
}

function setFastTimeout (callback, delay, opaque) {
const timer = {
callback,
delay,
expires: fastNow + delay,
opaque
}

fastTimers.add(timer)

return timer
}

function refreshFastTimeout (timer) {
if (timer) {
timer.expires = fastNow + timer.delay
}
}

function clearFastTimeout (timer) {
if (timer) {
fastTimers.delete(timer)
}
}

class Client extends DispatcherBase {
constructor (url, {
interceptors,
Expand Down Expand Up @@ -447,9 +487,9 @@ class Parser {
setTimeout (value, type) {
this.timeoutType = type
if (value !== this.timeoutValue) {
clearTimeout(this.timeout)
clearFastTimeout(this.timeout)
if (value) {
this.timeout = setTimeout(onParserTimeout, value, this)
this.timeout = setFastTimeout(onParserTimeout, value, this)
// istanbul ignore else: only for jest
if (this.timeout.unref) {
this.timeout.unref()
Expand All @@ -463,13 +503,12 @@ class Parser {
}
}

refreshTimeout() {
if (this.timeout) {
// istanbul ignore else: only for jest
if (this.timeout.refresh) {
this.timeout.refresh()
}
}
refreshTimeout () {
refreshFastTimeout(this.timeout)
}

clearTimeout () {
clearFastTimeout(this.timeout)
}

resume () {
Expand Down Expand Up @@ -566,7 +605,7 @@ class Parser {
this.llhttp.llhttp_free(this.ptr)
this.ptr = null

clearTimeout(this.timeout)
this.clearTimeout()
this.timeout = null
this.timeoutValue = null
this.timeoutType = null
Expand Down

0 comments on commit e0ffe52

Please sign in to comment.