Delay function execution until after a specified time has elapsed since the last invocation
Quick Answer
A debounce function delays execution of a callback until a set amount of time has passed since its last call. It is ideal for search inputs, resize handlers, and any scenario where you want to wait for user activity to pause before acting.
1function debounce(func, wait) {
2 let timeout;
3 return function executedFunction(...args) {
4 const later = () => {
5 clearTimeout(timeout);
6 func(...args);
7 };
8 clearTimeout(timeout);
9 timeout = setTimeout(later, wait);
10 };
11}A debounce function is a higher-order function that delays the execution of a callback until a certain amount of time has passed without it being called again. This is particularly useful for optimizing performance in scenarios where you want to limit how often a function runs, such as handling search inputs, window resize events, or scroll listeners.
Debounce delays execution until activity stops for a set time. Throttle ensures the function runs at most once per interval, regardless of how many times it is called.
200–400 ms is a common range. 300 ms is a good default — short enough to feel responsive, long enough to avoid firing on every keystroke.
Yes. Wrap the function in useCallback with an empty dependency array so a new debounced function is not created on every render.
This free javascript code snippet for debounce function is production-ready and copy-paste friendly. Whether you are building a web app, API, or frontend interface, this intermediate-level example will help you implement debounce function quickly and correctly.
All snippets in the Snippetly library follow javascript best practices and are tested for real-world use. You can adapt this code to work with React, Vue, Node.js, or any project that uses javascript.
Organise your team's code snippets with Snippetly. Share knowledge and boost productivity across your organisation.