Front-end performance optimization – anti – shake and throttling

Anti-shake and throttling should strictly be considered performance optimization knowledge, but in practice they are encountered quite frequently and can cause browsers to freeze if handled improperly or left unchecked. So it is necessary to master early.

It is said that one of Ali’s interview questions is about function throttling and function stabilization.

Debounce

Debounce: When an event is continuously triggered and no event is triggered again within the specified period, the event handler is executed once. If the event is triggered again before the specified period ends, the delay is restarted.

For an intuitive comparison, let’s look at the Click event without the Debounce technique:

We saw that when the user clicked the button frequently, the console output results frequently. This frequent call to the event handler burdened the browser and made the user experience very bad.

To solve this problem, we can use debounce in our coding.

Anti-shake principle: It maintains a timer and triggers the function after the specified delay time. However, if triggered again within the delay time, the previous timer will be cancelled and reset. In this way, only the last operation can be triggered.

Look at a 🌰 (chestnut) :

function debounce(fn, delay) {
  var timer = null;
  return function() {
     // Clear an existing timer
     timer && clearTimeout(timer)
     timer = setTimeout(function() {
        fn.apply(this)
     }, delay)
  }
}
let $btn = document.getElementById('btn');
var fn = function() {
  console.log ('Anti-shake is designed to trigger only the last execution in a period of time' + new Date(Date.now()));
}
$btn.onclick = debounce(fn, 1000);
Copy the code

As shown in the figure, the click event will not be executed every time the click event is continuously triggered. The click event will be delayed only when no more click event is triggered within the set period of 1000 ms.

Throttle

Function throttling: When a function is executed once, it is executed a second time only after the specified execution period. Ensure that event handlers are called only once in a certain period of time when events are continuously raised.

Throttle translated into throttle valve, we can imagine that we are releasing water from the faucet. As soon as the valve is opened, the water will flow down in a splash. In accordance with the fine traditional virtue of thrift, we should turn the faucet down a little, and it is better to drip drip in a certain time interval according to a certain law as we wish.

Similarly, let’s first look at the Scroll event without throttle, as shown below:

All of these frequent Scroll operations are taxing the browser, so let’s look at throttle.

Throttling principle: Records the last timestamp lastTime, records the current timestamp nowTime when an event is triggered, and checks whether the difference between nowTime and lastTime is greater than the set period delay. If so, the callback is executed and the last timestamp is updated. The frequency at which event handlers are fired is guaranteed over a period of time when events are continuously fired.

Here’s another 🌰 :

function throttle(fn, delay) {
  // Record the timestamp of the last trigger
  var lastTime = 0;
  return function() {
     // Record the timestamp of the current trigger
     var nowTime = Date.now();
     // Execution is allowed if the time difference between the current trigger and the last trigger is greater than the set period
     if (nowTime - lastTime > delay) {
        fn.call(this);
        // Update the timestamplastTime = nowTime; }}}document.onscroll = function () {
  console.log ('Throttling is designed to control the frequency of the trigger over time.'+new Date(Date.now()))
}
Copy the code

As shown in the following figure, when the Scroll event is continuously triggered, the handler function will not be executed immediately. The handler function will be executed only when the time difference between the current triggering and the last triggering is greater than the set period.

Application scenarios

The principle and implementation of debounce and throttle are described above.

The following is a brief list of the application scenarios of both:

Application scenarios of Debounce:

  • Each resizing/scrolling triggers a statistical event.
  • Validate text input (After successive text input, send an Ajax request for validation).
  • Monitor scroll events (scrolling after adding jitter is not determined until the user stops scrolling if it has reached the bottom of the page).

Throttle application scenarios:

  • Implement the DOM element drag and drop function mousemove.
  • Search for associated KeyUp.
  • Calculate mouse movement distance mousemove.
  • Canvas simulation sketch feature mousemove.
  • Mousedown/KeyDown events in shooters (only one – bullet per unit of time).
  • Monitor scroll events (with the addition of throttling, the scroll will be calculated at regular intervals).

conclusion

  • Function stabilization and function throttling both prevent frequent triggering at one time, but the two brothers work differently.
  • Function stabilization is performed only once in a certain period of time, while function throttling is performed at intervals.

Phase to recommend

High frequency JavaScript interview question summary

✍ topic

What answer will you never forget? When you’re a student, you often hear two arguments about memory:

1. Rote memorization: effective quickly, but also quickly forgotten, and generally not flexible use (indicators do not cure the root cause)

2. Understanding memory: Slow to effect, but long-lasting and flexible to use (treating both symptoms and causes)

Which would you like to pick?