Skip to content

Commit

Permalink
Merge pull request #15 from percy507/main
Browse files Browse the repository at this point in the history
fix: reset `innerStart` variable if passed time is greater than `wait` ms
  • Loading branch information
manuelpuyol authored Feb 27, 2023
2 parents 825a7e0 + ce1c296 commit 514b201
Show file tree
Hide file tree
Showing 2 changed files with 30 additions and 2 deletions.
10 changes: 8 additions & 2 deletions index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -23,15 +23,21 @@ export function throttle<T extends unknown[]>(
wait = 0,
{start = true, middle = true, once = false}: ThrottleOptions = {}
): Throttler<T> {
let innerStart = start
let last = 0
let timer: ReturnType<typeof setTimeout>
let cancelled = false
function fn(this: unknown, ...args: T) {
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) {
Expand Down
22 changes: 22 additions & 0 deletions test/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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)
Expand Down Expand Up @@ -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)
Expand Down

0 comments on commit 514b201

Please sign in to comment.