Back to library
📜JavaScriptjavascriptintermediate

Debounce Function

Delay function execution until after a specified time has elapsed since the last invocation

performanceoptimizationtiming

Code

1function debounce(func, wait) {
2  let timeout;
3  
4  return function executedFunction(...args) {
5    const later = () => {
6      clearTimeout(timeout);
7      func(...args);
8    };
9    
10    clearTimeout(timeout);
11    timeout = setTimeout(later, wait);
12  };
13}
14
15// Usage example
16const handleSearch = debounce((query) => {
17  console.log('Searching for:', query);
18  // Perform search operation
19}, 300);
20
21// Call handleSearch multiple times
22handleSearch('hello'); // Won't execute
23handleSearch('hello world'); // Only this will execute after 300ms

Quick Tips

  • Click the "Copy" button to copy the code to your clipboard
  • This code is production-ready and can be used in your projects
  • Check out related snippets below for more examples

Related Snippets

Build Your Own Snippet Library

Organize your team's code snippets with Snippetly. Share knowledge and boost productivity across your organization.