Skip to content

Commit

Permalink
Merge pull request #2 from netinsight-flugund/master
Browse files Browse the repository at this point in the history
Add a flag to avoid promise / clearTimout race
  • Loading branch information
mattiash committed Mar 7, 2019
2 parents 8202aaa + e0f63aa commit 63bfad3
Show file tree
Hide file tree
Showing 2 changed files with 13 additions and 0 deletions.
5 changes: 5 additions & 0 deletions index.ts
Expand Up @@ -20,9 +20,13 @@ export function setRandomizedIntervalAsync(
) {
let ref = true
let currTimer: NodeJS.Timeout
let clear = false

let fn = () => {
callback(...args).then(() => {
if (clear) {
return
}
currTimer = setTimeout(fn, interval(ms))
if (!ref) {
currTimer.unref()
Expand All @@ -34,6 +38,7 @@ export function setRandomizedIntervalAsync(

return {
clear: () => {
clear = true
clearTimeout(currTimer)
},
unref: () => {
Expand Down
8 changes: 8 additions & 0 deletions test/test-basic.ts
Expand Up @@ -64,6 +64,14 @@ test('unref()', function*(t) {
t.pass('if the test exits, the unref() was successful')
})

test('setRandomizedInterval clear()', function(t) {
let t1 = setRandomizedInterval(() => {
t1.clear()
}, 100)

t.pass('if the test exits, the clear() was successful')
})

function wait(ms: number) {
return new Promise(resolve => setTimeout(resolve, ms))
}

0 comments on commit 63bfad3

Please sign in to comment.