This is the 10th day of my participation in the Gwen Challenge.More article challenges

First taste of “Anti-shake and Throttling in JavaScript”

What is anti-shake and throttling? I’m sure it’s not the first time you’ve heard of these two terms in daily learning. So what exactly are anti-vibration and throttling?

When an event is triggered, the action is delayed for a period of time. If the event is triggered again, the action is reset until the end of the period. You can perform an action only once when you throttle a specified period. If a new event is triggered, you do not perform the action. After the cycle ends, another event is triggered to start a new cycle.

Lao for a long time the basic concept, so we come to the actual operation some time ~.

First experience of anti-shake

First let’s take a look at the initial code

<body> Input box with no shaker function: <inputclass="input"/>
    
  </input>
</body>

<script>
  let  input =document.querySelector('.input');
  function ajax(content) {
    console.log("Network request sent.", content);
  }
  input.addEventListener('keyup'.(e) = > {
    ajax(e.target.value)
  })
  // If we use the keyboard to type in the input frenzy, we will call the Ajax function many times, and the call will not make any sense.
  
</script>
Copy the code

Next we’ll write a debounce function

  function debounce(fun, timer) {
    return function (args) {
      let   that = this
      let _args = args
      fun.id = setTimeout(function(){
        fun.call(that, _args)
      }, timer)
    }
  }

  let debounceAjax = debounce(ajax, 500)  
  input.addEventListener('keyup'.function(e) {
    debounceAjax()
  })
  Declare a function and let it call another function to form a closure. And inside the other function there's a 500 millisecond timer,
  // When the function is called, the timer sends an Ajax request, but if the function is called within 500 milliseconds then it will be clear that the previous timer is cleared again. Until the next timer is not interrupted.
  
Copy the code

Meet throttling

So let’s cut to the code

  function throttle(fun, timer) {
    let last, deferTimer
    return function (args) {
      let   that = this
      let _args = arguments
      let now = +new Date(a)if(last && now < last + timer){
        clearTimeout(deferTimer)
      deferTimer = setTimeout(function(){
        fun.call(that, _args)
      }, timer)
      }else{
        last = now
        fun.call(that, _args)
      }
    }
  }
  
  let throttleAjax = throttle(ajax, 500) 
  
  // Last = now if the function is not found, then call the function to send ajax request. And then throttle makes a mercy call and if last or now is greater than my current 500 milliseconds then I know the timer and I'm creating a timer and sending an Ajax request at the same time
Copy the code