Image stabilization (debounce)

Trigger the same event for a certain amount of time, and the function will only execute after the last click.

It can be understood as “return to the city skill” in the game. After pressing the button, you need to wait for a period of time to return to the city. Any time you press the button during the process, you need to wait again.

// func is a function that the user passes in to be buffed
// Wait is the time to wait
function debounce(fn, wait) {
    let timer = null // with closure
    return function(. args) {
        // Enter the branch statement, indicating that a timing process is currently underway and the same event is triggered again.
        // Cancel the current timer and start the timer again
        if (timer) clearTimeout(timer) 
        timer = setTimeout(() = > {
            fn.apply(this, args)
        }, wait) // Enter the branch to indicate that no time is currently being timed, so start a timer}}Copy the code

The throttle (throttle)

If the same event is triggered within a certain period of time and the function is executed immediately, the function will not work for the specified period of time. The function will take effect again after the specified period of time.

It can be understood as a “normal skill” in the game. It will trigger immediately after being pressed, but no matter how you press the button after the skill is triggered, you need to wait for a certain cooldown before triggering again.

// func is a function passed in by the user to be throttled
// Wait is the time to wait
function throttle(fn, wait) {
    // The last time this function was executed
    let lastTime = 0
    return function(. args) {
        // The current time
        let now = +new Date(a)// Compare the current time to the last time the function was executed
        // If the difference is greater than the set wait time, the function is executed
        if (now - lastTime > wait) {
            lastTime = now
            fn.apply(this, args)
        }
    }
}
Copy the code

Example:

Post a case study and immediately experience the effects of anti-shake and throttling.

<body>
  <button id="btn1">If you click</button>
  <button id="btn2">Throttling click</button>
  <script>
    function debounce(fn, wait) {
      let timer = null
      return function (. args) {
        if (timer) clearTimeout(timer) 
        timer = setTimeout(() = > {
          fn.apply(this, args)
        }, wait)
      }
    }

    function throttle(fn, wait) {
      let lastTime = 0
      return function (. args) {
        let now = +new Date(a)if (now - lastTime > wait) {
          lastTime = now
          fn.apply(this, args)
        }
      }
    }

    function say() {
      console.log('-------hello-------')}document.getElementById('btn1').onclick = debounce(say, 2000)
    document.getElementById('btn2').onclick = throttle(say, 2000)
  </script>
</body>
Copy the code