Delay function execution until after a specified time has elapsed since the last invocation
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 300msOrganize your team's code snippets with Snippetly. Share knowledge and boost productivity across your organization.