Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Adding trigger function. #41

Merged
merged 3 commits into from
May 25, 2024
Merged
Show file tree
Hide file tree
Changes from 1 commit
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
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;
olafurw marked this conversation as resolved.
Show resolved Hide resolved
};

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();
});