1.38.0debounce
Delays function execution until a specified amount of time has passed since the last call.
debounce(fn, delay):(...args: TArgs) => voidParameters
fn(...args: TArgs) => voidrequiredThe function to execute after the delay has passed without another call.
delaynumberrequiredThe delay in milliseconds before the function is executed.
Returns
(...args: TArgs) => voidA debounced function that resets its timer whenever it is called.
Examples
Basic usage
The function executes after the specified delay.
import { debounce } from "@cyref/js";
const logMessage = debounce(() => {
console.log("Executed");
}, 500);
logMessage();Resetting the delay
Calling the debounced function again clears the previous timeout and starts the delay again.
import { debounce } from "@cyref/js";
const search = debounce((query: string) => {
console.log("Searching:", query);
}, 500);
search("c");
search("cy");
search("cyref");
// Only the last call is executed after 500ms.
// Searching: cyrefPassing arguments
Arguments passed to the debounced function are forwarded to the original function when it executes.
import { debounce } from "@cyref/js";
const greet = debounce((name: string) => {
console.log(`Hello, ${name}!`);
}, 300);
greet("Amir");
// After 300ms:
// Hello, Amir!Multiple arguments
The debounced function supports multiple arguments with the same types as the original function.
import { debounce } from "@cyref/js";
const calculate = debounce(
(a: number, b: number) => {
console.log(a + b);
},
500,
);
calculate(10, 20);
// After 500ms:
// 30Repeated calls
Only the most recent call is executed when multiple calls occur before the delay expires.
import { debounce } from "@cyref/js";
const save = debounce((value: string) => {
console.log("Saved:", value);
}, 1000);
save("first");
setTimeout(() => {
save("second");
}, 300);
setTimeout(() => {
save("third");
}, 600);
// Only "third" is executed after the final 1000ms delay.
// Saved: thirdUseful for input events
debounce can delay frequently triggered callbacks such as input or search events.
import { debounce } from "@cyref/js";
const handleSearch = debounce((value: string) => {
console.log("Search:", value);
}, 400);
handleSearch("Java");
handleSearch("JavaScript");
// Only the latest call is executed after 400ms.
// Search: JavaScript