Skip to content

Instantly share code, notes, and snippets.

@deptno
Created June 9, 2018 20:14
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save deptno/bc486be03daf04e5f29984e200515030 to your computer and use it in GitHub Desktop.
Save deptno/bc486be03daf04e5f29984e200515030 to your computer and use it in GitHub Desktop.
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