Current limiting

In JS, if an event is fired frequently (for example, when the user clicks a button crazily) and the handler takes a long time to process, it can cause performance problems.

The flow limiting function is one of the optimization methods for this kind of problem. It requires that the two event processing must be longer than a certain interval time. In short, it adds a layer of judgment.

The core of the throttle function is to internally maintain a “last execution point”, which determines whether the execution is “frequent” and whether the execution is performed by comparing the difference between the current execution time and the last execution time. The stream limiting function itself is a decorator function that decorates the event handler and returns a new closure. After being processed by the stream limiting function, events are limited to firing above the pre-passed interval.

The following code to implement a limiting function:

function throttle(fn, interval) {
  // Maintain the last execution time
  let last = 0;

  return function () {
    const context = this;
    const args = arguments;
    const now = Date.now();
    // Determine the frequency based on the difference between the current time and the last execution time
    if(now - last >= interval) { last = now; fn.apply(context, args); }}; }Copy the code

Using the current limiting function:

<! DOCTYPEhtml>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <meta
      name="viewport"
      content="Width =device-width, user-scalable=no, initial-scale=1.0, maximum-scale=1.0, minimum-scale=1.0"
    />
    <meta http-equiv="X-UA-Compatible" content="ie=edge" />
    <title>Document</title>
  </head>
  <body>
    <button>click me</button>
    <script src="./throttle.js"></script>
    <script>
      const button = document.querySelector("button");
      button.addEventListener(
        "click".// Decorate the event handler with a stream limiting function
        throttle((event) = > {
          console.log("button click");
        }, 2000));</script>
  </body>
</html>
Copy the code

Image stabilization

The anti – shake function is also a current limiting function, but in a special way. The most typical scenario is form input, if we want to in the form to monitor the input events (such as remote search), when the user in the input will trigger frequently, but here not use throttle function, because we need to stop waiting for user input after a period of time to confirm that the user input values, so to define a new current limiting function, It’s called the anti-shake function.

The core of the anti-shake (anti-bounce) function is to use the timer internally and maintain the ID value returned by the timer. If the timer is continuously triggered, it will continuously clearTimeout() and restart setTimeout(). In this way, it will wait for the event to be triggered and then delay processing.

The following code to achieve a tremble function:

function debounce(fn, delay) {
  // Records the ID returned by the timer
  let timer = null;

  return function () {
    const context = this;
    const args = arguments;
    // Clears the previous scheduled task when an event is triggered
    if (timer) {
      clearTimeout(timer);
    }
    // Re-initiate a scheduled task
    timer = setTimeout(() = > {
      fn.apply(context, args);
    }, delay);
  };
}
Copy the code

Use the anti-shake function:

<! DOCTYPEhtml>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <meta
      name="viewport"
      content="Width =device-width, user-scalable=no, initial-scale=1.0, maximum-scale=1.0, minimum-scale=1.0"
    />
    <meta http-equiv="X-UA-Compatible" content="ie=edge" />
    <title>Document</title>
  </head>
  <body>
    <input type="text" />
    <script src="debounce.js"></script>
    <script>
      const input = document.querySelector("input");
      input.addEventListener(
        "input",
        debounce((event) = > {
          console.log("input finish");
        }, 2000));</script>
  </body>
</html>
Copy the code

You can refer to the LoDash library for these commonly used functions

conclusion

Both the flow limiting function and the stabilization function are optimizations for situations where the event processing speed can’t keep up with the event firing speed.

Throttle requires an interval between event processing, and debounce requires execution after the last event has been triggered.