Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
throttle-does-not-guarantee-latest-call
import {throttle, debounce} from 'lodash'
const delay = () => new Promise(r => setTimeout(r, 100))
describe('throttle vs debouce', () => {
beforeEach(() => {
console.log = jest.fn()
})
it('throttle does not guarantee about execute latest call', async (done) => {
const i = throttle(x => console.log(x), 300)
let count = 0
i(++count)
await delay()
i(++count)
await delay()
i(++count)
await delay()
i(++count)
await delay()
i(++count)
await delay()
i(++count)
await delay()
i(++count)
await delay()
i(++count)
await delay()
i(++count)
await delay()
i(++count)
await delay()
await delay()
expect(count).toEqual(10)
expect(console.log).not.toHaveBeenLastCalledWith(10)
done()
})
it('debounce guarantee about execute latest call', async (done) => {
const i = debounce(x => console.log(x), 200)
let count = 0
i(++count)
await delay()
i(++count)
await delay()
i(++count)
await delay()
i(++count)
await delay()
i(++count)
await delay()
i(++count)
await delay()
i(++count)
await delay()
i(++count)
await delay()
i(++count)
await delay()
await delay()
await delay()
expect(count).toEqual(9)
// expect(console.log).toHaveBeenCalledTimes(1)
expect(console.log).toHaveBeenLastCalledWith(9)
done()
})
})
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment