Write a function named debounce
that receives one parameter:
callback
The debounce
function should return a new function, let's name it debouncedCallback
that will behave exactly like callback
but it will only run when at least 1000ms
have passed without it being invoked again.
const printSum = (a, b) => {
console.log(a + b);
}
const debouncedPrintSum = debounce(printSum);
debouncedPrintSum(1, 2);
debouncedPrintSum(11, 12);
debouncedPrintSum(100, 200);
/**
* The number 300 should be printed to the console
* after with a 1 second delay. That's because the
* function is debounced so it only runs if it hasn't
* been invoked for 1000ms. The first two calls are
* thus ignored, and the last one will be executed.
*/
const printSum = (a, b) => {
console.log(a + b);
}
const debouncedPrintSum = debounce(printSum);
debouncedPrintSum(1, 2);
debouncedPrintSum(3, 4);
debouncedPrintSum(5, 6);
setTimeot(() => {
debouncedPrintSum(7, 8);
debouncedPrintSum(9, 10);
debouncedPrintSum(11, 12);
}, 2000)
/**
* Running the code above should:
* 1. Print the number `11` after 1 second
* 2. Print the number `23` after 3 more seconds
*
* That's because the function is debounced
* and the only invocations that actually run are:
* - `debouncedPrintSum(100, 200);`
* - `debouncedPrintSum(100, 200);`
*/