Skip to content

Commit e0ffe52

Browse files
committed
perf: fast timers
1 parent 6b96f5a commit e0ffe52

File tree

1 file changed

+49
-10
lines changed

1 file changed

+49
-10
lines changed

lib/client.js

Lines changed: 49 additions & 10 deletions
Original file line numberDiff line numberDiff line change
@@ -83,6 +83,46 @@ try {
8383
channels.connected = { hasSubscribers: false }
8484
}
8585

86+
let fastNow = Date.now()
87+
const fastTimers = new Set()
88+
const fastNowInterval = setInterval(() => {
89+
fastNow = Date.now()
90+
for (const timer of fastTimers) {
91+
if (fastNow >= timer.expires) {
92+
timer.expires = 0
93+
timer.callback(timer.opaque)
94+
}
95+
}
96+
}, 1e3)
97+
if (fastNowInterval.unref) {
98+
fastNowInterval.unref()
99+
}
100+
101+
function setFastTimeout (callback, delay, opaque) {
102+
const timer = {
103+
callback,
104+
delay,
105+
expires: fastNow + delay,
106+
opaque
107+
}
108+
109+
fastTimers.add(timer)
110+
111+
return timer
112+
}
113+
114+
function refreshFastTimeout (timer) {
115+
if (timer) {
116+
timer.expires = fastNow + timer.delay
117+
}
118+
}
119+
120+
function clearFastTimeout (timer) {
121+
if (timer) {
122+
fastTimers.delete(timer)
123+
}
124+
}
125+
86126
class Client extends DispatcherBase {
87127
constructor (url, {
88128
interceptors,
@@ -447,9 +487,9 @@ class Parser {
447487
setTimeout (value, type) {
448488
this.timeoutType = type
449489
if (value !== this.timeoutValue) {
450-
clearTimeout(this.timeout)
490+
clearFastTimeout(this.timeout)
451491
if (value) {
452-
this.timeout = setTimeout(onParserTimeout, value, this)
492+
this.timeout = setFastTimeout(onParserTimeout, value, this)
453493
// istanbul ignore else: only for jest
454494
if (this.timeout.unref) {
455495
this.timeout.unref()
@@ -463,13 +503,12 @@ class Parser {
463503
}
464504
}
465505

466-
refreshTimeout() {
467-
if (this.timeout) {
468-
// istanbul ignore else: only for jest
469-
if (this.timeout.refresh) {
470-
this.timeout.refresh()
471-
}
472-
}
506+
refreshTimeout () {
507+
refreshFastTimeout(this.timeout)
508+
}
509+
510+
clearTimeout () {
511+
clearFastTimeout(this.timeout)
473512
}
474513

475514
resume () {
@@ -566,7 +605,7 @@ class Parser {
566605
this.llhttp.llhttp_free(this.ptr)
567606
this.ptr = null
568607

569-
clearTimeout(this.timeout)
608+
this.clearTimeout()
570609
this.timeout = null
571610
this.timeoutValue = null
572611
this.timeoutType = null

0 commit comments

Comments
 (0)