diff --git a/index.ts b/index.ts index dd46b6b..634410d 100644 --- a/index.ts +++ b/index.ts @@ -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() @@ -34,6 +38,7 @@ export function setRandomizedIntervalAsync( return { clear: () => { + clear = true clearTimeout(currTimer) }, unref: () => { diff --git a/test/test-basic.ts b/test/test-basic.ts index daf8058..4e0617c 100644 --- a/test/test-basic.ts +++ b/test/test-basic.ts @@ -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)) }