JavaScript anti-shake and throttling

Why should there be anti-shake and throttling

If the frequency of the event handler calls is unlimited, which can burden the browser and lead to a terrible user experience, debounce and throttle can be used to reduce the frequency of calls without compromising the actual performance


A, stabilization,

When an event is continuously triggered and no event is triggered again within a certain period of time, the event handler will execute once. If the event is triggered again before the specified time, the delay will start again

As follows: The input event will be output only if the event is not triggered within 2000 ms when it is input, and the input event will be re-timed if it is started again within 2000 ms

<div>
  <input class="inp" type="text" />
</div>
<script>
  let input = document.querySelector('.inp')
  let timer = null

  / / image stabilization
  input.addEventListener('input'.function () {
    // console.log(input.value)
    clearTimeout(timer)
    timer = setTimeout(function () {
      console.log(input.value)
    }, 2000)})</script>
Copy the code

The effect


Second, the throttle

When continuous triggering event, guarantee period only calls an event handler throttling popular explanation for example, we tap water, the valve is opened, the water stream flowing downwards, with the advantages and good traditional virtue of thrift, we have to turn down the faucet, it is best if we will according to certain rules in a certain interval drip drip down

As follows: the mouse movement event will trigger the timer function once within 100 milliseconds, but not infinitely

<div>
  <h1 class="z">coordinates</h1>
</div>
<script>
  let z = document.querySelector('.z')
  let timer = null
  document.addEventListener('mousemove'.function (e) {
    if(timer ! = =null) return
    timer = setTimeout(function () {
      console.log(e.clientX, e.clientY)
      z.innerHTML = 'coordinate' + '(' + e.clientX + ', ' + e.clientY + ') '
      timer = null
    }, 100)})</script>
Copy the code

The effect