Anti-shake and throttling

First, why is it necessary to prevent shaking and throttle

During business writing, elements are often bound to many events. If the event is triggered repeatedly and continuously during event execution, unnecessary performance problems may occur and experience may be affected. Triggered from an optimization point of view, the event needs to be buffered and throttled.

Such as the following scenarios:

  • Click the button to submit the form (multiple clicks)
  • Page scrolling
  • Input box: Enter fuzzy search
  • .

Two, what is function tremble

When the event is triggered, start the timer. If the event is triggered again within the specified time, it will clear the last timer, and then restart the timer to ensure that the event is not triggered again within the specified time, and then execute the event.

In simple terms, it is triggered multiple times within a specified period of time, and can only be executed once (you can control whether it is executed at the beginning or the last time). If the submit form button is clicked multiple times, it will be executed only once in a certain period of time

/** * anti-shake *@param {fnc} function
 * @param {wait} Number Indicates the delay for executing *@param {immediate} Boolean whether to execute * immediately the first time it is triggered@return {function}* /
function debounce(func, wait, immediate) {
    if (typeoffunc ! = ='function') throw new TypeError('func must be an function! ')
    if (typeof wait === 'undefined') wait = 500
    if (typeof wait === 'boolean') {
        immediate = wait
        wait = 500
    }
    if (typeofimmediate ! = ='boolean') immediate = false

    // Set the timer return value identifier
    let timer = null;
    return function proxy(. params) {
        let self = this
        
        // The first execution takes place only when the immediate is true and no timer exists
        letnow = immediate && ! timerclearTimeout(timer);
        timer = setTimeout(function () {
            timer = null;
            if(! immediate) { func.call(self, ... params) } }, wait);// Execute immediately on the first trigger
        if(now) { func.call(self, ... params) } }; }/ / use
function handle(e) {
    // Business to be processed at click time
    console.log(this, e)
}

document.getElementById('submit').addEventListener('click', debounce(handle, true))
Copy the code

Third, what is function throttling

Under a certain high-frequency trigger, it is not only recognized once, but in accordance with the set interval time (the frequency specified by itself), every time it reaches this frequency will be triggered once; Assuming that the specified frequency is 500MS, and we operate for 1min, the number of triggers is (1 * 60 * 1000) / 500, which can be understood as reducing the execution frequency. Use scenarios such as: mostly for listening to page elements scroll

/** * throttle *@param {fnc} function
 * @param {wait} Number Indicates the interval for triggering events *@return {function}* /
function throttle(func, wait) {
  if (typeoffunc ! = ='function') {
      throw new TypeError('func must be an function! ')}if (typeof wait === 'undefined') wait = 500
  
  let timer = null,
    previous = 0 // Record the last operation time
    
  return function proxy(. params) {
    let self = this,
      now = new Date(), // The current trigger operation time
      remaining = wait - (now - previous)
      
    if (remaining <= 0) {
      // If the interval is longer than wait, execute it directly
      clearTimeout(timer)
      timer = nullprevious = now func.call(self, ... params) }else if(! timer) {// If the interval between triggers does not exceed wait, set the timer
      // Make it wait for remaining to execute "Prerequisite: No timer is set" once.
      timer = setTimeout(function () {
        clearTimeout(timer)
        timer = null
        previous = new Date() func.call(self, ... params) }, remaining) } } }/ / use
function handle() {
  console.log('throttle')}window.onscroll = throttle(handle, 500)
Copy the code