📜  debounce js - Javascript (1)

📅  最后修改于: 2023-12-03 14:40:41.619000             🧑  作者: Mango

Debounce in JavaScript

Debouncing is a technique used in JavaScript to limit the number of times a function is executed based on a certain interval. This is useful in scenarios where a function may be triggered multiple times in a short period, such as when a user is typing in an input field.

Why use debounce?

Using debounce improves the performance of your application by reducing the number of times a function is executed. For example, if you have an event listener for a scroll event that makes a network request to fetch data, using debounce will ensure that the request is only made after the user has stopped scrolling for a defined amount of time.

How does debounce work?

Debouncing works by setting a timer when a function is executed. If the function is executed again before the timer has completed, the timer is reset. This continues until the timer has completed without the function being executed. Once the timer is complete, the function is executed.

Here's an example of how to implement debounce in JavaScript:

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

const myFunction = () => {
  console.log('Function executed');
}

const debouncedFunction = debounce(myFunction, 1000);

window.addEventListener('scroll', debouncedFunction);

In this example, we define a debounce function which takes two arguments: the func function to be executed, and the delay in milliseconds. We then return an anonymous function that will be executed when the debouncedFunction is called.

Inside the anonymous function, we set a timer using setTimeout and store the return value in timeoutId. We then clear the timer using clearTimeout and reset the timer by calling setTimeout again with the func and delay arguments.

Finally, we call apply on the func function with context and args as arguments to ensure that the function is executed in the correct context with the correct arguments.

We then define a myFunction function which will be executed once the debouncedFunction timer has completed. We create a debouncedFunction variable by calling debounce with myFunction and a delay of 1000 milliseconds.

We then add a scroll event listener to the window object that will execute debouncedFunction when the user scrolls.

Conclusion

Debouncing in JavaScript is a useful technique for improving performance by limiting the number of times a function is executed. By using debounce, you can ensure that your application runs smoothly and efficiently, especially in scenarios where a function may be executed multiple times in a short period.