When you want to implement a delay when invoking a function, leveraging a debounce
function can help.
A good example would be using it for something like a live search input where you might be hitting an API to retrieve some search results. Constantly hitting the API on each keystroke could be wasteful.
const debounce = <T extends (...args: any[]) => ReturnType<T>>(
callback: T,
timeout: number
): ((...args: Parameters<T>) => void) => {
let timer: ReturnType<typeof setTimeout>
return (...args: Parameters<T>) => {
clearTimeout(timer)
timer = setTimeout(() => {
callback(...args)
}, timeout)
}
}
const myDebouncedFunction = debounce(e => {
console.log(e)
}, 3000)
myDebouncedFunction('Hello world')
// Console logs 'Hello world' after 3 seconds
const myDebouncedFunction = debounce((name: string, location: string) => {
console.log(`My name is ${name} and I am in ${location}`)
}, 3000)
myDebouncedFunction('Amit', 'the UK')
// Console logs 'My name is Amit and I am in the UK' after 3 seconds
const greeting = (name: string, location: string) => {
console.log(`My name is ${name} and I am in ${location}`)
}
debounce(greeting, 3000)('Amit', 'the UK')
// Console logs 'My name is Amit and I am in the UK' after 3 seconds