Skip to content

Commit

Permalink
Tweak reentry guard (#4)
Browse files Browse the repository at this point in the history
  • Loading branch information
mafintosh authored Oct 2, 2024
1 parent 5c2c47c commit 518552c
Show file tree
Hide file tree
Showing 3 changed files with 19 additions and 4 deletions.
8 changes: 4 additions & 4 deletions index.js
Original file line number Diff line number Diff line change
Expand Up @@ -26,7 +26,7 @@ class Timer {
this._expiry = now + this._list.ms
this._list.push(this)
} else {
if (this._refed === true) this.unref()
if (this._refed === true) decRef()
this._list = null
}
// apply at the bottom to avoid re-entries...
Expand All @@ -36,7 +36,7 @@ class Timer {
_clear () {
if (this._list === null) return
this._list.clear(this)
if (this._refed === true) this.unref()
if (this._refed === true) decRef()
this._list = null

maybeUpdateTimer()
Expand All @@ -57,14 +57,14 @@ class Timer {
}

unref () {
if (this._refed === false) return this
if (this._refed === false || this._list === null) return this
this._refed = false
decRef()
return this
}

ref () {
if (this._refed === true) return this
if (this._refed === true || this._list === null) return this
this._refed = true
incRef()
return this
Expand Down
1 change: 1 addition & 0 deletions test/all.js
Original file line number Diff line number Diff line change
@@ -1,3 +1,4 @@
require('./immediate')
require('./interval')
require('./timeout')
require('./ref') // has to be last one
14 changes: 14 additions & 0 deletions test/unref.js → test/ref.js
Original file line number Diff line number Diff line change
Expand Up @@ -13,3 +13,17 @@ test('unref and a timer stays alive', async function (t) {
}, 50)
}
})

// must be last test!
test('ref in callbacks are noops', async function (t) {
t.plan(1)

const timer = timers.setTimeout(run, 10)

function run () {
timer.ref()
const other = timers.setTimeout(() => t.fail('should not run'), 10_000)
other.unref()
t.pass('timer triggered')
}
})

0 comments on commit 518552c

Please sign in to comment.