Handwriting anti – shake and throttling

Idle time to have a tight mind, busy time to have leisure fun

  • Nuggets team number online, help you Offer impromptu! Click for details

directory

  • preface

  • The body of the

    • 1. Debounce
    • Ii. Throttle
  • conclusion

  • Reference documentation

preface

Returns the directory

Ask questions and don’t talk nonsense.

The body of the

1. Debounce

Returns the directory

Anti-shake, as the name implies, to prevent jitter, so as not to mistake an event for many times, typing the keyboard is a daily contact with anti-shake operation.

The principle of

  • If you don’t want a task to be triggered too often, set a timer at a specified interval to delay its execution.
  • Every time you come in, you clear the timer and start it again.
  • The task is executed only when the interval triggered by the task exceeds the specified interval.

The characteristics of

  • If the task is triggered again within the specified interval (such as 1000ms), the current timing is cancelled, all tasks are not executed, and the timing is restarted.
  • If the task is not triggered again within a specified interval (such as 1000ms), the last task is executed

That is, if triggered too often, there will be no response at all. The last task can be executed only after the specified interval (such as 1000ms) is triggered for the last time.

Application scenarios

  • To prevent users from clicking buttons such as login and SMS so fast that multiple requests are sent, you need to avoid shaking
  • When adjusting the browser window size, the number of resize times is too frequent, resulting in too much calculation. At this time, it needs to be in place once, so it uses anti-shake
  • The text editor saves in real time and saves after one second when there is no change operation

Code implementation

ClearTimeout (Timer)

/** * anti-shake *@param {String} Fn callback method *@param {String} Delay Buffer time */

function debounce(fn, delay) {
  // Create a flag to store the timer
  let timeout = null
  return function () {
    // Each time the function fires, the previous timer is cleared
    clearTimeout(timeout)
    // Create a new setTimeout
    // This ensures the delay time interval after clicking the button
    // If the user still clicks, the fn function will not be executed
    timeout = setTimeout(() = > {
      // Use apply to correct this pointer and execute the passed function
      fn.apply(this.arguments)
    }, delay)
  }
}
Copy the code

Ii. Throttle

Throttling, as the name suggests, controls the flow of water. Control the frequency of events, such as 1 second, or even 1 minute. This parameter is similar to the Rate Limit controlled by the server and gateway.

The principle of

  • Initialize a switch lock to true
  • Sets the closure function to execute only if the tag is true and then false
  • A timer within a closure at a specified interval delays the execution of the task, and then sets the tag to true.

The characteristics of

  • No matter how many tasks are triggered within a specified interval (such as 1000ms), only the first task is executed
  • The first task must be executed after the specified interval (such as 1000ms) at which the task is triggered.

That is, as long as you fire a task, it must be executed after a specified interval (such as 1000ms) and only the first time. The cycle repeats.

Application scenarios

  • Scroll event, calculate position information every second, etc
  • Browser plays events, calculates progress information every second, and so on
  • Input box Search and send requests in real time display dropdown list, send requests every second (also can be made to shake)

Code implementation

“Throttle on switch lock”

/** * throttle *@param {String} Fn callback method *@param {String} Delay Buffer time */

function throttle(fn, delay) {
  // Initialize a state to be true
  let canRun = true
  return function () {
    // Do not accept customers during the rest time
    if(! canRun) {return
    }
    // Work time, execute function;
    // Set the status bit to false during the interval
    canRun = false
    // Create a timer to delay task execution
    setTimeout(() = > {
      // Use apply to correct this pointer and execute the passed function
      fn.apply(this.arguments)
      // After executing the task, reset the flag to true
      canRun = true
    }, delay)
  }
}
Copy the code

conclusion

Returns the directory

Start a handwritten series.

The road ahead is long, and I see no end.

reference

  • Jsliang cover series – 12 – handwritten image stabilization and throttling | the nuggets – jsliang
  • Introduction to JS stabilization and throttling | – Ann song

Attached demo code

<div>
  <button id="debounceBtn">Let me offer</button>
  <button id="throttleBtn">Let me choke</button>
</div>

<script>
  // Number of button clicks
  let clickNum = 0
  // Button click time
  let clickTime = 0
  // The time when the button starts clicking
  let startTime = 0
  // Execution time
  let executionTime = 0
  // Get the button
  const debounceBtn = document.getElementById('debounceBtn')
  const throttleBtn = document.getElementById('throttleBtn')
  // Bind the click event
  debounceBtn.onclick = function (e) {
    clickBtn()
    debounceFn(clickNum)
  }
  throttleBtn.onclick = function (e) {
    clickBtn()
    throttleFn(clickNum)
  }

  // Throttling and anti-shake events
  let debounceFn = debounce(fnExecution, 1000)
  let throttleFn = throttle(fnExecution, 1000)

  // Click button event
  function clickBtn() {
    clickNum++
    clickTime = Date.now()
    if (clickNum === 1) {
      startTime = Date.now()
    }
    console.log(` this is the first${clickNum}Click `)}function fnExecution(num) {
    executionTime = Date.now()
    console.log(
      'Effective is no${num}Click, the interval between the effective time and the last click is${ executionTime - clickTime }Milliseconds, the interval between the effective time and the first click is${executionTime - startTime}Ms `
    )
    clickNum = 0
  }

  /** * anti-shake *@param {String} Fn callback method *@param {String} Delay Buffer time */

  function debounce(fn, delay) {
    // Create a flag to store the timer
    let timeout = null
    return function () {
      // Each time the function fires, the previous timer is cleared
      clearTimeout(timeout)
      // Create a new setTimeout
      // This ensures the delay time interval after clicking the button
      // If the user still clicks, the fn function will not be executed
      timeout = setTimeout(() = > {
        // Use apply to correct this pointer and execute the passed function
        fn.apply(this.arguments)
      }, delay)
    }
  }

  /** * throttle *@param {String} Fn callback method *@param {String} Delay Buffer time */

  function throttle(fn, delay) {
    // Initialize a state to be true
    let canRun = true
    return function () {
      // Do not accept customers during the rest time
      if(! canRun) {return
      }
      // Work time, execute function;
      // Set the status bit to false during the interval
      canRun = false
      // Create a timer to delay task execution
      setTimeout(() = > {
        // Use apply to correct this pointer and execute the passed function
        fn.apply(this.arguments)
        // After executing the task, reset the flag to true
        canRun = true
      }, delay)
    }
  }
</script>
Copy the code

Postscript: Hello friends, if you think this article is good, remember to give a thumbs-up or star, your thumbs-up and star is my motivation to write more and richer articles!Making the address

Document agreement



dbThe document library 由 dbusingCreative Commons Attribution – Non-commercial Use – Same way Share 4.0 International LicenseGrant permission.

Based on thegithub.com/danygitgitOn the creation of works.

Use rights other than those authorized by this License agreement may be obtained from
Creativecommons.org/licenses/by…Obtained.