Created
March 20, 2021 09:57
-
-
Save sidhantpanda/253f09e0f6ff9c316fb8b6018c130943 to your computer and use it in GitHub Desktop.
Debounce in TypeScript
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/** | |
* 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