mirror of
https://github.com/woocommerce/woocommerce-paypal-payments.git
synced 2025-08-31 06:52:50 +08:00
✨ Extend the debounce helper with flush & cancel
This commit is contained in:
parent
9629c86447
commit
317ba4e8ec
1 changed files with 45 additions and 6 deletions
|
@ -1,9 +1,48 @@
|
|||
export const debounce = ( callback, delayMs ) => {
|
||||
let timeoutId = null;
|
||||
return ( ...args ) => {
|
||||
window.clearTimeout( timeoutId );
|
||||
timeoutId = window.setTimeout( () => {
|
||||
callback.apply( null, args );
|
||||
}, delayMs );
|
||||
const state = {
|
||||
timeoutId: null,
|
||||
args: null,
|
||||
};
|
||||
|
||||
/**
|
||||
* Cancels any pending debounced execution.
|
||||
* @return {boolean} True if a pending execution was cancelled, false otherwise.
|
||||
*/
|
||||
const cancel = () => {
|
||||
if ( ! state.timeoutId ) {
|
||||
return false;
|
||||
}
|
||||
|
||||
window.clearTimeout( state.timeoutId );
|
||||
state.timeoutId = null;
|
||||
state.args = null;
|
||||
return true;
|
||||
};
|
||||
|
||||
/**
|
||||
* Immediately executes the debounced function if there's a pending execution.
|
||||
* @return {void}
|
||||
*/
|
||||
const flush = () => {
|
||||
const args = state.args;
|
||||
|
||||
// If there's nothing pending, return early.
|
||||
if ( ! cancel() ) {
|
||||
return;
|
||||
}
|
||||
|
||||
callback.apply( null, args || [] );
|
||||
};
|
||||
|
||||
const debouncedFunc = ( ...args ) => {
|
||||
cancel();
|
||||
state.args = args;
|
||||
state.timeoutId = window.setTimeout( flush, delayMs );
|
||||
};
|
||||
|
||||
// Attach utility methods
|
||||
debouncedFunc.cancel = cancel;
|
||||
debouncedFunc.flush = flush;
|
||||
|
||||
return debouncedFunc;
|
||||
};
|
||||
|
|
Loading…
Add table
Add a link
Reference in a new issue