From 1cd49f8ed4fbde0e3d2226338088d36e3d25ce98 Mon Sep 17 00:00:00 2001 From: percy507 Date: Fri, 17 Feb 2023 09:58:22 +0800 Subject: [PATCH] fix: reset `innerStart` variable if passed time is greater than `wait` ms --- index.ts | 10 ++++++++-- test/index.ts | 22 ++++++++++++++++++++++ 2 files changed, 30 insertions(+), 2 deletions(-) diff --git a/index.ts b/index.ts index 9a4ba35..c2ad037 100644 --- a/index.ts +++ b/index.ts @@ -23,6 +23,7 @@ export function throttle( wait = 0, {start = true, middle = true, once = false}: ThrottleOptions = {} ): Throttler { + let innerStart = start let last = 0 let timer: ReturnType let cancelled = false @@ -30,8 +31,13 @@ export function throttle( if (cancelled) return const delta = Date.now() - last last = Date.now() - if (start) { - start = false + + if (start && middle && delta >= wait) { + innerStart = true + } + + if (innerStart) { + innerStart = false callback.apply(this, args) if (once) fn.cancel() } else if ((middle && delta < wait) || !middle) { diff --git a/test/index.ts b/test/index.ts index 00e84fe..1637cfc 100644 --- a/test/index.ts +++ b/test/index.ts @@ -49,6 +49,17 @@ describe('throttle', () => { expect(calls).to.eql([[1], [3]]) }) + it('will fire even the passed time greater than `wait` ms', async () => { + fn(1) + await delay(200) + fn(2) + fn(3) + fn(4) + await delay(1000) + fn(5) + expect(calls).to.eql([[1], [2], [4], [5]]) + }) + it('calls callback with given arguments (middle)', async () => { fn(1, 2, 3) fn(4, 5, 6) @@ -131,6 +142,17 @@ describe('debounce (throttle with {start: false, middle: false})', () => { expect(calls).to.eql([[3]]) }) + it('will fire even the passed time greater than `wait` ms', async () => { + fn(1) + await delay(200) + fn(2) + fn(3) + fn(4) + await delay(1000) + fn(5) + expect(calls).to.eql([[1], [4]]) + }) + it('exposes `this`', async () => { fn = debounce(function (this: unknown) { calls.push(this)