When writing the case of Pick Color card before, I took into account the problem of clicking copy key for many times, so I realized the idea of throttling after consulting the data, and made a record here.

Knowledge supplement

1. What is anti-shake?

Anti-shake means that the callback is executed n seconds after the event is triggered. If the event is triggered again within n seconds, the timer is reset.

For example, a button can be specified to respond after it is clicked for 0.5s. If it is clicked again within 0.5s, the timer will be reset and the response can be made as long as it is not clicked again within 0.5s.

There is another concept related to anti – shake, that is throttling.

2. What is throttling?

Throttling refers to specifying a unit of time within which only one trigger event can be executed. If the event is triggered multiple times within the same unit of time, only one trigger can take effect.

For example, if a button is clicked multiple times, it should respond only once per unit of time.

3. How to achieve function tremble or throttling?

Hey, how about a setTimeout()?

╯ ╰ (° del °)

(1) Hand tear anti shake function

Implementation idea: set a timer, if triggered again, we will empty the previous timer, a new timer.

<button id="debounce"</button> <script> window.onload =function() {
    var myDebounce = document.getElementById("debounce");
    myDebounce.addEventListener("click", debounce(sayDebounce)); } // The function fn is the next function to be calledfunctionDebounce (fn) {// Create a timerlet timeout = null;
    return function() {// Each time the user clicks again, use clearTimeout() to set the previous timersetThe Timeout () to remove clearTimeout (Timeout); // Create a new onesetTimeout, // If the user still clicks, the fn function will not be executedsetTimeout(() => {
        fn.call(this, arguments);
      }, 1000);
    };
  }

  function sayDebounce() {/ /... Some work that needs to be shaken out console.log((o゚v゚)/");
  }

</script>
Copy the code
(2) Hand tear throttling function

Implementation idea: Trigger the function by determining whether the unit time is reached.

<button id="throttle"> throttle (o゚v゚)</button> <script> window.onload =function() {
    var myThrottle = document.getElementById("throttle");
    myThrottle.addEventListener("click", throttle(sayThrottle)); } // throttling functionfunctionThrottle (fn) {// Whether var canRun = can be executed by saving a flag through a closuretrue;
    return function() {// If marked astrueYou can executeif(! canRun) {return; } // Set the tag tofalseTo prevent canRun = from being executed before executionfalse; / / timersetTimeout( () => { fn.call(this, arguments); // After execution, re-set the flag totrue
        canRun = true;
      }, 2000);
    };
  }

  function sayThrottle() {
    console.log("Throttle successful! (o゚v゚)/");
  }
</script>
Copy the code

My practical application

In Pick Color, there are three corresponding HEX/RGB/HSL buttons. What I want to achieve is that users clicking on the button can get the corresponding text to be saved on the clipboard. How about this display bar showing ‘copied’ for two seconds? With the words.

->


Therefore, THERE are two problems I need to solve: first, I hope to make the user click 0.5s before making a response, so as to prevent multiple clicks and multiple responses; The second is to keep the div unclicked and unresponsive while copying the word ‘2s’.

Therefore, after learning the anti-shake, I set a time interval of 0.5s, hoping to avoid multiple clicks by users:

var colorHsl = document.getElementsByClassName("copy-hsl") [0]; colorHsl.addEventListener("click", debounce(sayDebounce))

function debounce(fn) {
  let timeout = null;
  return function() {
    clearTimeout(timeout); 
    timeout = setTimeout(() => {
      fn.call(this, arguments);
    }, 500);
  };
}

function sayDebounce(){
  var pickColor = this.innerHTML;
  copyToClipboard(pickColor);
  this.innerHTML = "copied!"
  var time = 0;
  setTimeout(() => { this.innerHTML = pickColor; }, 2000); }Copy the code

Second, I chose to set a class property for the div after ‘copying’ and set pointers-events to null, meaning that the element will never be the target of mouse events and therefore will not trigger click events

.no-click{
    pointer-events: none;
}
Copy the code

Refer to the link

The nuggets | jsliang | 2019 interview preparation – JS stabilization and throttling

The last

Throttling and anti-shaking is a very common point of performance optimization, I also learned this knowledge in the process of the project, in this article to record, if there is anything wrong in this article, I hope you can correct.

Also attached Pick Color Color card project source code: Pick Color source code

This article is formatted using MDNICE