Back to Snippets

Debounce Function

javascript
JavaScript

A utility function to limit how often a function can be called. Perfect for search inputs and resize handlers.

Code

1function debounce(func, wait) {
2let timeout;
3return function executedFunction(...args) {
4const later = () => {
5clearTimeout(timeout);
6func(...args);
7};
8clearTimeout(timeout);
9timeout = setTimeout(later, wait);
10};
11}
12
13// Usage
14const debouncedSearch = debounce((query) => {
15console.log("Searching for:", query);
16}, 300);

Details

Language

javascript

Category

JavaScript