Skip to content

Commit

Permalink
Adding trigger and tests.
Browse files Browse the repository at this point in the history
  • Loading branch information
olafurw committed May 23, 2024
1 parent 691098b commit 13acb02
Show file tree
Hide file tree
Showing 2 changed files with 30 additions and 0 deletions.
13 changes: 13 additions & 0 deletions index.js
Original file line number Diff line number Diff line change
Expand Up @@ -84,6 +84,19 @@ function debounce(function_, wait = 100, options = {}) {
timeoutId = undefined;
};

debounced.trigger = () => {
const callContext = storedContext;
const callArguments = storedArguments;
storedContext = undefined;
storedArguments = undefined;
result = function_.apply(callContext, callArguments);

if (timeoutId) {
clearTimeout(timeoutId);
timeoutId = undefined;
}
};

return debounced;
}

Expand Down
17 changes: 17 additions & 0 deletions test.js
Original file line number Diff line number Diff line change
Expand Up @@ -397,3 +397,20 @@ test('calling flush method without any scheduled execution', async () => {

assert.strictEqual(callback.callCount, 0, 'Callback should not be executed if flush is called without any scheduled execution');
});

test('calling the trigger function should run it immediately', async () => {
const clock = sinon.useFakeTimers();
const callback = sinon.spy();
const fn = debounce(callback, 100);

fn();
fn.trigger();

assert.strictEqual(callback.callCount, 1, 'Callback should be called once when using trigger method');

clock.tick(100);

assert.strictEqual(callback.callCount, 1, 'Callback should stay at one call after timeout');

clock.restore();
});

0 comments on commit 13acb02

Please sign in to comment.