Skip to content

Commit 514b201

Browse files
authored
Merge pull request #15 from percy507/main
fix: reset `innerStart` variable if passed time is greater than `wait` ms
2 parents 825a7e0 + ce1c296 commit 514b201

File tree

2 files changed

+30
-2
lines changed

2 files changed

+30
-2
lines changed

index.ts

+8-2
Original file line numberDiff line numberDiff line change
@@ -23,15 +23,21 @@ export function throttle<T extends unknown[]>(
2323
wait = 0,
2424
{start = true, middle = true, once = false}: ThrottleOptions = {}
2525
): Throttler<T> {
26+
let innerStart = start
2627
let last = 0
2728
let timer: ReturnType<typeof setTimeout>
2829
let cancelled = false
2930
function fn(this: unknown, ...args: T) {
3031
if (cancelled) return
3132
const delta = Date.now() - last
3233
last = Date.now()
33-
if (start) {
34-
start = false
34+
35+
if (start && middle && delta >= wait) {
36+
innerStart = true
37+
}
38+
39+
if (innerStart) {
40+
innerStart = false
3541
callback.apply(this, args)
3642
if (once) fn.cancel()
3743
} else if ((middle && delta < wait) || !middle) {

test/index.ts

+22
Original file line numberDiff line numberDiff line change
@@ -49,6 +49,17 @@ describe('throttle', () => {
4949
expect(calls).to.eql([[1], [3]])
5050
})
5151

52+
it('will fire even the passed time greater than `wait` ms', async () => {
53+
fn(1)
54+
await delay(200)
55+
fn(2)
56+
fn(3)
57+
fn(4)
58+
await delay(1000)
59+
fn(5)
60+
expect(calls).to.eql([[1], [2], [4], [5]])
61+
})
62+
5263
it('calls callback with given arguments (middle)', async () => {
5364
fn(1, 2, 3)
5465
fn(4, 5, 6)
@@ -131,6 +142,17 @@ describe('debounce (throttle with {start: false, middle: false})', () => {
131142
expect(calls).to.eql([[3]])
132143
})
133144

145+
it('will fire even the passed time greater than `wait` ms', async () => {
146+
fn(1)
147+
await delay(200)
148+
fn(2)
149+
fn(3)
150+
fn(4)
151+
await delay(1000)
152+
fn(5)
153+
expect(calls).to.eql([[1], [4]])
154+
})
155+
134156
it('exposes `this`', async () => {
135157
fn = debounce(function (this: unknown) {
136158
calls.push(this)

0 commit comments

Comments
 (0)