0
0
JavascriptHow-ToBeginner · 3 min read

How to Debounce Function in JavaScript: Simple Guide

To debounce a function in JavaScript, wrap it inside another function that delays its execution until a specified wait time has passed since the last call. Use setTimeout to schedule the call and clearTimeout to reset the timer if the function is called again quickly.
📐

Syntax

The debounce function takes two main parts: the function to debounce and the delay time in milliseconds. It returns a new function that controls when the original function runs.

  • func: The function you want to delay.
  • wait: Time in milliseconds to wait before calling func.
  • The returned function resets the timer every time it is called, so func only runs after wait ms of no calls.
javascript
function debounce(func, wait) {
  let timeout;
  return function(...args) {
    clearTimeout(timeout);
    timeout = setTimeout(() => func.apply(this, args), wait);
  };
}
💻

Example

This example shows a debounced function that logs a message only after 500 milliseconds have passed without new calls. Rapid calls will delay the log until the calls stop.

javascript
function debounce(func, wait) {
  let timeout;
  return function(...args) {
    clearTimeout(timeout);
    timeout = setTimeout(() => func.apply(this, args), wait);
  };
}

const debouncedLog = debounce(() => console.log('Function called!'), 500);

// Simulate rapid calls
debouncedLog();
debouncedLog();
debouncedLog();

// Only one 'Function called!' will print after 500ms
Output
Function called!
⚠️

Common Pitfalls

Common mistakes include not clearing the previous timer, which causes the function to run multiple times, or losing the correct this context and arguments inside the debounced function.

Always use clearTimeout before setting a new timer and use func.apply(this, args) to keep context and arguments.

javascript
/* Wrong way: missing clearTimeout, causes multiple calls */
function wrongDebounce(func, wait) {
  let timeout;
  return function(...args) {
    timeout = setTimeout(() => func.apply(this, args), wait);
  };
}

/* Right way: clearTimeout resets timer */
function rightDebounce(func, wait) {
  let timeout;
  return function(...args) {
    clearTimeout(timeout);
    timeout = setTimeout(() => func.apply(this, args), wait);
  };
}
📊

Quick Reference

Debounce Tips:

  • Use clearTimeout to reset the timer on each call.
  • Use setTimeout to delay the function execution.
  • Preserve this and arguments with func.apply(this, args).
  • Debounce is useful for events like resizing, scrolling, or typing.

Key Takeaways

Debounce delays function execution until calls stop for a set time.
Always clear the previous timer with clearTimeout to avoid multiple calls.
Use func.apply(this, args) to keep the original function's context and arguments.
Debouncing improves performance for frequent events like typing or resizing.
The returned function from debounce controls when the original function runs.