Skip to content

Commit

Permalink
fix(watchThrottled): wait incorrect remaining time (#2267)
Browse files Browse the repository at this point in the history
  • Loading branch information
sun0day committed Oct 25, 2022
1 parent bcedacd commit fb39a68
Show file tree
Hide file tree
Showing 4 changed files with 22 additions and 5 deletions.
2 changes: 1 addition & 1 deletion packages/shared/utils/filters.ts
Expand Up @@ -134,7 +134,7 @@ export function throttleFilter(ms: MaybeComputedRef<number>, trailing = true, le
isLeading = true
clear()
invoke()
}, duration)
}, duration - elapsed)
}

if (!leading && !timer)
Expand Down
17 changes: 17 additions & 0 deletions packages/shared/utils/index.test.ts
Expand Up @@ -120,6 +120,23 @@ describe('filters', () => {
expect(debouncedFilterSpy).toHaveBeenCalledTimes(2)
})

it('should throttle evenly', () => {
const debouncedFilterSpy = vitest.fn()

const filter = createFilterWrapper(throttleFilter(1000), debouncedFilterSpy)

setTimeout(() => filter(1), 500)
setTimeout(() => filter(2), 1000)
setTimeout(() => filter(3), 2000)

vitest.runAllTimers()

expect(debouncedFilterSpy).toHaveBeenCalledTimes(3)
expect(debouncedFilterSpy).toHaveBeenCalledWith(1)
expect(debouncedFilterSpy).toHaveBeenCalledWith(2)
expect(debouncedFilterSpy).toHaveBeenCalledWith(3)
})

it('should throttle with ref', () => {
const debouncedFilterSpy = vitest.fn()
const throttle = ref(0)
Expand Down
2 changes: 1 addition & 1 deletion packages/shared/watchDebounced/index.test.ts
Expand Up @@ -39,7 +39,7 @@ describe('watchDebounced', () => {
expect(cb).toHaveBeenCalledTimes(1)

num.value = 5
await promiseTimeout(70)
await promiseTimeout(75)
expect(cb).toHaveBeenCalledTimes(2)
expect(cb).toHaveBeenCalledWith(4, 2, expect.anything())
})
Expand Down
6 changes: 3 additions & 3 deletions packages/shared/watchThrottled/index.test.ts
Expand Up @@ -23,12 +23,12 @@ describe('watchThrottled', () => {

num.value = 3
await promiseTimeout(50)
expect(cb).toHaveBeenCalledTimes(1)
expect(cb).toHaveBeenCalledWith(1, 0, expect.anything())
expect(cb).toHaveBeenCalledTimes(2)
expect(cb).toHaveBeenCalledWith(3, 2, expect.anything())

num.value = 4
await promiseTimeout(100)
expect(cb).toHaveBeenCalledTimes(2)
expect(cb).toHaveBeenCalledTimes(3)
expect(cb).toHaveBeenCalledWith(4, 3, expect.anything())
})
})

0 comments on commit fb39a68

Please sign in to comment.