diff --git a/lib/assets/javascripts/utils/debounce.js b/lib/assets/javascripts/utils/debounce.js index 8013d68..4c3c68d 100644 --- a/lib/assets/javascripts/utils/debounce.js +++ b/lib/assets/javascripts/utils/debounce.js @@ -1,15 +1,16 @@ import { isFunction, isNumber } from './isType'; export default function debounce(func, wait) { - if (isFunction(func) && (wait || isNumber(wait))) { + if (isFunction(func)) { let timeoutID = null; + const delay = isNumber(wait) ? wait : 1000; const closureDebounce = (...args) => { const delayed = () => { timeoutID = null; func.apply(this, args); }; clearTimeout(timeoutID); - timeoutID = setTimeout(delayed, wait || 1000); + timeoutID = setTimeout(delayed, delay); }; closureDebounce.cancel = () => { if (timeoutID) { diff --git a/lib/assets/javascripts/utils/debounceSpec.js b/lib/assets/javascripts/utils/debounceSpec.js new file mode 100644 index 0000000..c5803df --- /dev/null +++ b/lib/assets/javascripts/utils/debounceSpec.js @@ -0,0 +1,68 @@ +import debounce from './debounce'; + +describe('debounce test suite', () => { + let functionToDebounce; + + beforeEach(() => { + functionToDebounce = jasmine.createSpy('My function to debounce'); + jasmine.clock().install(); + }); + + afterEach(() => { + jasmine.clock().uninstall(); + }); + + it('functionToDebounce gets called after the time specified', () => { + const debounced = debounce(functionToDebounce, 1000); + + debounced('foo', 'bar'); + + expect(functionToDebounce).not.toHaveBeenCalled(); + + jasmine.clock().tick(1001); + + expect(functionToDebounce).toHaveBeenCalled(); + expect(functionToDebounce.calls.first().args[0]).toBe('foo'); + expect(functionToDebounce.calls.first().args[1]).toBe('bar'); + }); + + it('functionToDebounce gets cancelled before time elapses', () => { + const debounced = debounce(functionToDebounce, 1000); + + debounced('foo', 'bar'); + + jasmine.clock().tick(999); + debounced.cancel(); + jasmine.clock().tick(2); + + expect(functionToDebounce).not.toHaveBeenCalled(); + }); + + it('functionToDebounce gets called once after the time specified', () => { + const debounced = debounce(functionToDebounce, 1000); + + debounced('foo', 'bar'); + jasmine.clock().tick(999); + debounced('foo', 'bar'); + jasmine.clock().tick(999); + debounced('foo', 'bar'); + jasmine.clock().tick(1001); + + expect(functionToDebounce.calls.count()).toBe(1); + }); + + it('functionToDebounce gets called once after the time specified with args of last invocation', () => { + const debounced = debounce(functionToDebounce, 1000); + + debounced('foo', 'bar'); + jasmine.clock().tick(999); + debounced('foo2', 'bar2'); + jasmine.clock().tick(999); + debounced('foo3', 'bar3'); + jasmine.clock().tick(1001); + + expect(functionToDebounce.calls.count()).toBe(1); + expect(functionToDebounce.calls.first().args[0]).toBe('foo3'); + expect(functionToDebounce.calls.first().args[1]).toBe('bar3'); + }); +});