This article is participating in the nuggets team online activity, clickCheck spring recruitment positions in big factories

1. Title Description

  • Write an anti-shake and throttling function

Second, train of thought analysis

Image stabilization

  • When an event is triggered consecutively within a specified period of time, it is executed only once
  • You can use a timersetTimeoutTo determine the timing of execution, for example, we set the time interval as 100ms, that is, within 100ms after triggering the event, if the event does not continue to trigger, then the system has been stable and can execute the operation, otherwise, the timing will continue to wait for stability of 100ms

The throttle

  • Throttling: When an event is fired continuously, this function is executed at a specific time interval
  • Similarly, if we set the interval to 100ms, we will execute events every 100ms if we fire them consecutively

Three, code implementation

Image stabilization

const debounce = (fn, delay) = > {
    let timer = null
    return () = > {
        if (timer) {  / / is true. The event is triggered when it should not be executed. Therefore, you need to clear the event
            clearTimeout(timer)
        }
        timer = setTimeout(fn, delay)
    }
}
Copy the code

The throttle

const throttle = (fn, delay) = > {
  let valid = true // Whether to run flag
  return () = > {
    if(! valid) {return
    }
    valid = false
    setTimeout(() = > { // Delay triggered to reset the execution flag
      fn()
      valid = true //
    }, delay)
  }
}
Copy the code

Four,

  • Usage Scenarios:

    • Anti – shake: adjust window size, monitor screen rolling events, mouse movement, etc., only trigger the last time within the specified time
    • Throttling: Real-time search function. Trigger events at a specific frequency
  • The specific application scenario depends on the number of times they need to be executed. If they are executed once, the number of times is throttling