Throttling and debouncing

1. Concept

Throttling and debouncing are two performance optimization techniques commonly used when handling user input and other events. Their main purpose is to control the frequency of event triggering to avoid unnecessary repeated operations, reduce system burden, and improve user experience.

1.Throttling:

  • Throttling is a technique that limits the execution frequency of event handling functions, ensuring that events are executed at most once within a certain time interval.
  • When an event is triggered, throttling will immediately execute the event handler function and ignore any subsequent triggers of the same event within the specified time interval.
  • Suitable for operations that require regular updates, such as scroll events and search box input, to ensure that they are not triggered too frequently and reduce the burden on the server and client.

2. Debouncing:

  • Anti-shake is a technology that delays the execution of event processing functions to ensure that after an event is triggered, no more events are triggered within a specified time before the event processing function is executed.
  • When an event is triggered, anti-shake will wait for a period of time. If no more events are triggered within this period, the event handler will be executed.
  • It is suitable for scenarios where you need to wait for the user to stop typing, etc. to prevent repeated submission of forms, search suggestions, etc.

2. Differences

1. Triggering method: Throttling is to execute the event processing function at most once within a certain time interval, while anti-shaking is to wait for a period of time and then execute the event processing function. If there is a new trigger event during the waiting period, The waiting time will be reset.

2. Application scenarios: Throttling is suitable for scenarios where the frequency of events needs to be limited to ensure that events are triggered within a certain interval; anti-shake is suitable for scenarios where the user needs to stop the operation before execution, such as search suggestions, Input box validation.

In short: upon initialization, throttling will execute the event handler once immediately, while anti-shaking will not be executed on initialization. Anti-shake will only execute the event processing function after the event is triggered and the event is not triggered again within the specified waiting time. This is the key difference between the two.

3. Code implementation

Throttling:

function throttle(fn, delay) {
  let lastExecutionTime = 0;
  return function(...args) {
    const currentTime = Date.now();
    if (currentTime - lastExecutionTime >= delay) {
      fn(...args);
      lastExecutionTime = currentTime;
    }
  };
}

Anti-Shake:

function debounce(fn, delay) {
    let timer;
    return function (...args) {
        clearTimeout(timer);
        timer = setTimeout(() => {
        fn(...args);
        }, delay);
    };
}

Note: In the anti-shake function, cannot be written as timer = setTimeout(fn(…args), delay); A function reference should be passed instead of calling fn directly. The anti-shake function requires that fn be executed after delay milliseconds, rather than immediately.

4. Demo

1. Throttle Demo: Page scrolling will trigger printing, and printing can only be performed once within three seconds to avoid frequent page scrolling and multiple printings.

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
</head>
<body>
    <div style="height:8000px; background-color:pink"></div>
    <script>
        function throttle(fn, delay){
            let lastExecutionTime = 0;
            return function(...args) {
                const currentTime = Date.now();
                if(currentTime - lastExecutionTime >= delay){
                    fn(...args);
                    lastExecutionTime = currentTime;
                }
            }
        }
        // Using the throttling function, printing can only be triggered once within 3 seconds.
        window.addEventListener('scroll', throttle(function() {
            console.log('Scroll event triggered!');
        }, 3000));
    </script>
</body>
</html>

2. Anti-shake Demo: input in the input box will trigger printing. After stopping input, if there is no further input within 1 second, it will print. If input is made, the time will be reset for 1 second.

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
</head>
<body>
    <input type="text" id="searchInput">
    <script>
        function debounce(fn, delay) {
            let timer;
            return function (...args) {
                clearTimeout(timer);
                timer = setTimeout(() => {
                fn(...args);
                }, delay);
            };
        }
        const searchInput = document.getElementById('searchInput');
        searchInput.addEventListener('input', debounce(function() {
                console.log("Execute once");
        }, 1000));
    </script>
</body>
</html>

5. Practical application

1. Scroll event handling:

  • Throttling: Used to limit the frequency of scroll event processing to reduce the number of scroll event processing, thereby improving performance.
  • Anti-shake: Used to delay the execution of scroll event processing to ensure that related operations, such as loading more data, are triggered after the user completes the scroll operation.

2. Window resize event:

  • Throttling: Used to limit the frequency of event processing when the window size is continuously adjusted to avoid excessive redraw operations.
  • Anti-Shake: Used to ensure that the corresponding adjustment operation is only performed after the user stops resizing the window.

3. The search box is automatically completed:

  • Anti-shake: Used to delay the automatic completion of search operations when the user enters search keywords to reduce the number of requests and reduce the load on the server.

4. Form input validation:

  • Anti-shake: Used to delay validation operations when users enter form fields to reduce the frequency of validation requests.

5. Button click event:

  • Throttling: Used to limit the frequency of button click events to avoid repeated operations caused by multiple clicks by the user.

6. Live chat:

  • Anti-shake: Used in real-time chat applications to delay sending user-entered messages to reduce network requests and improve performance.

7. Carousel image switching:

  • Throttling: Used to limit the frequency of carousel image switching to improve user experience and prevent users from switching images quickly.

8. Mouse movement event:

  • Throttling: Used to limit the frequency of mouse movement events to reduce the number of processing and improve performance.

6. Supplementary instructions

During development, we can manually write a throttling or anti-shake function, or we can use lodash’s _.throttle and _.debounce.

Usage example (provided lodash has been imported):

const throttledFunction = _.throttle(function () {
  console.log("Throttled function called");
}, 1000);

// Usage example:
window.addEventListener("scroll", throttledFunction);
const debouncedFunction = _.debounce(function () {
  console.log("Debounced function called");
}, 500);

// Usage example:
document.querySelector("input").addEventListener("input", debouncedFunction);