The dboun function is a utility designed to limit the rate at which a function is executed. It ensures that the provided function (fn) is called only after a specified delay (delay) has elapsed since the last invocation. By default, the delay is set to 400 milliseconds.
This is particularly useful for handling events that fire frequently, such as resizing, scrolling, or typing, by preventing the provided function from being called excessively.
// Define the function to handle search function handleSearch(query: string): void { console.log("Searching for:", query); } // Create a debounced version of the search handler const debouncedSearch = dboun(handleSearch, 300); // Simulate typing in a search box const input = document.querySelector('#searchBox'); input?.addEventListener('input', (event: Event) => { const target = event.target as HTMLInputElement; debouncedSearch(target.value); });
In this example:
fn (Function): The function to be executed after the debounce delay.
delay (Number, optional): The number of milliseconds to wait before invoking fn. Defaults to 400 milliseconds.
The dboun function returns a new debounced version of fn. The returned function delays the invocation of fn until after delay milliseconds have passed since the last time the returned function was called.
The dboun function uses modern JavaScript/TypeScript features, making it compatible with most modern environments. For older environments, consider transpiling the code.
// Test debounced function const log = dboun((message: string) => console.log(message), 500); log("Hello"); // Will not log immediately log("Hello again"); // Resets the timer; only this message will log after 500ms
The above is the detailed content of Dboun. For more information, please follow other related articles on the PHP Chinese website!