JavaScript Answers

How to perform a debounce with JavaScript?

Spread the love

Debouncing is a technique used to limit the rate at which a function is called. It’s particularly useful when dealing with events that may trigger a function multiple times in a short period, such as scrolling, typing, or resizing.

Here’s a simple implementation of debouncing in JavaScript:

function debounce(func, delay) {
  let timeoutId;
  return function() {
    const context = this;
    const args = arguments;
    timeoutId = setTimeout(() => {
      func.apply(context, args);
    }, delay);

This debounce function takes two parameters:

  1. func: The function to be debounced.
  2. delay: The delay (in milliseconds) after which the debounced function should be called.

It returns a new function that wraps around the original function (func). This new function will only invoke func after the delay milliseconds have passed since the last invocation. If the debounced function is called again within the delay period, the timeout is reset, preventing the original function from being called until the delay period has elapsed.

Here’s an example of using the debounce function:

function handleInput() {
  console.log('Handling input...');

const debouncedHandleInput = debounce(handleInput, 300);

// Attach the debounced function to an event listener
inputElement.addEventListener('input', debouncedHandleInput);

In this example, handleInput is the function we want to debounce, and debouncedHandleInput is the debounced version of handleInput created using the debounce function. We attach debouncedHandleInput to an event listener (e.g., for an input event), ensuring that handleInput is only called after a certain delay once the event has stopped firing. Adjust the delay according to our requirements.

By John Au-Yeung

Web developer specializing in React, Vue, and front end development.

Leave a Reply

Your email address will not be published. Required fields are marked *