Skip to content

Instantly share code, notes, and snippets.

@johncmunson
Created July 28, 2020 17:57
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 johncmunson/0c03d5223f247d32b84246112a81c1e2 to your computer and use it in GitHub Desktop.
Save johncmunson/0c03d5223f247d32b84246112a81c1e2 to your computer and use it in GitHub Desktop.
Debounce a function, with the option to accumulate args
export function debounce(delay, callback, accumulateData) {
let timeout = null
let data = []
return function () {
if (accumulateData) {
const arr = []
for (let i = 0; i < arguments.length; ++i) {
arr.push(arguments[i])
}
data.push(arr)
}
if (timeout) {
clearTimeout(timeout)
}
const args = arguments
timeout = setTimeout(function () {
callback.apply((accumulateData) ? { data } : null, args)
data = []
timeout = null
}, delay)
}
}
// Unit tests should illustrate pretty well what this function does...
import { debounce } from '../../../src/util'
jest.useFakeTimers()
describe('util', () => {
describe('debounce', () => {
it('debounces the function', () => {
const target = jest.fn()
const func = function(int) {
target(int)
}
const debouncedFunc = debounce(1000, func, false)
debouncedFunc(1)
debouncedFunc(2)
debouncedFunc(3)
jest.runAllTimers()
expect(target).toHaveBeenCalledTimes(1)
expect(target).toHaveBeenCalledWith(3)
})
it('debounces the function and accumulates args', () => {
const target = jest.fn()
const func = function(int) {
target(this.data)
}
const debouncedFunc = debounce(1000, func, true)
debouncedFunc(1)
debouncedFunc(2)
debouncedFunc(3)
jest.runAllTimers()
debouncedFunc(4)
jest.runAllTimers()
expect(target).toHaveBeenCalledTimes(2)
expect(target.mock.calls[0][0]).toEqual([[ 1 ], [ 2 ], [ 3 ]])
expect(target.mock.calls[1][0]).toEqual([[ 4 ]])
})
})
})
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment