Skip to content

Instantly share code, notes, and snippets.

@sidhantpanda
Created March 20, 2021 09: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 sidhantpanda/253f09e0f6ff9c316fb8b6018c130943 to your computer and use it in GitHub Desktop.
Save sidhantpanda/253f09e0f6ff9c316fb8b6018c130943 to your computer and use it in GitHub Desktop.
Debounce in TypeScript
/**
* Debounce wrapper for functions which are called rapidly
* This wrapper ensures that there is a minimum wait time
* between function invocations.
* @param func Function to be called
* @param wait Minimum time between function calls
* @param immediate True if function needs to be invoked immediately,
* false if needs to be invoked after delay
* @returns Debounced function with the same signature as `func`
*/
const debounce = (func: Function, wait: number, immediate?: boolean): Function => {
let timeout: NodeJS.Timeout;
return function (...rest: any[]) {
const context = this;
const later = () => {
timeout = null;
if (!immediate) func.apply(context, rest);
};
const callNow = immediate && !timeout;
clearTimeout(timeout);
timeout = setTimeout(later, wait);
if (callNow) func.apply(context, rest);
};
};
const sleep = (time: number) => new Promise(resolve => setTimeout(resolve, time));
const logToConsole = function (...rest: any[]) {
const date = new Date();
console.log(`${date.getTime()}`, this.testValue || 'not preserved', ...rest);
};
const bouncedLog = debounce(logToConsole, 50, false);
const runner = async function () {
this.testValue = 'preserved';
logToConsole('imm1');
logToConsole('imm2');
logToConsole('imm3');
logToConsole('imm4');
bouncedLog('bounced1');
bouncedLog('bounced2');
bouncedLog('bounced3');
await sleep(50);
bouncedLog('bounced4');
bouncedLog('bounced5');
};
runner();
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment