Image stabilization (debounce)

Anti-shake, as the name suggests, prevents jitter to avoid executing the same event multiple times within a certain period of time.

Create a shake-out function that calls func after waiting milliseconds since the last call.

  1. First, we name the function (debounce) and pass two arguments: the first is the actual function that needs to be executed (func) and the second is the time to wait (wait).
function debounce(func, wait) {}
Copy the code
  1. Delay the call of func in milliseconds
function debounce(func, wait) {
    return setTimeout(func, wait || 1000)
}
Copy the code
  1. This is the most important step. If the function is called again in wait milliseconds, the last call will be cancelled and the func method will be called again in wait milliseconds. Here, the setTimeout and clearTimeout methods come to mind when you cancel the last call and postpone the call again. So let’s see how we can do that
function debounce(func, wait) {
    var timer
    return function() {
        clearTimeout(timer)
        setTimeout(func, wait| | 1000)}}Copy the code

The throttle (throttle)

Throttling, as the name suggests, saves traffic. Control the frequency of events, such as 1 second, or even 1 minute.

Create a throttling function that executes func at most once in wait seconds.

  1. First, we named the function throttle and passed two parameters: the first parameter is the actual function to execute (func) and the second parameter is the time to wait (wait).
function throttle(func, wait) {}
Copy the code
  1. Delay the call of func in milliseconds
function throttle(func, wait) {
    return setTimeout(func, wait || 1000)
}
Copy the code
  1. This step is the most critical. If the function is called again within wait milliseconds, it will be considered invalid and will not be executed. It is easy to create a variable whose Boolean value determines whether or not to execute the func function. So let’s see how we can do that
function throttle(func, wait) {
    var canrun = true
    return function() {
        if(! canrun)return
        canrun = false
        setTimeout(() => {
            func()
            canrun = true
        }, wait| | 1000)}}Copy the code
function throttle(cb, wait) {
  var timer
  return function() {
    if (timer) return
    timer = setTimeout(() => {
      cb()
      timer = null
    }, wait| | 1000)}}Copy the code

summary

Application scenarios of anti-shake function:

  • The button is clicked so fast that the function is executed multiple times
  • Resize the browser window too often, resulting in too much calculation
  • The text editor saves in real time and saves after one second when there is no change operation

Application scenarios of throttling functions

  • Scroll event, calculate position information every second, etc
  • Browser plays events, calculates progress information every second, and so on