What is anti-shake and throttling? Examples of application scenarios

Anti-shake

Anti-shake: The function will only be executed once within n seconds after a high-frequency event is triggered. If the high-frequency event is triggered again within n seconds, the time will be recalculated.

Application scenarios: Submit button, mobile phone number verification during user registration, email verification

Suppose we have a login button. If the user clicks the login button multiple times in a short period of time, the anti-shake technology can prevent the system from mistaking it as multiple login requests and only treat it as a valid login operation.

Throttle

Throttling: High-frequency events are triggered, but they will only be executed once within n seconds, so throttling will dilute the execution frequency of the function .

Application scenarios: resize of the window object, mousemove during scroll event dragging, mousedown, keydown event text input in shooting games, automatically completed keyup event

In scenarios such as window resizing, page scrolling, or rush shopping, we may need to use throttling to control the execution frequency of events to prevent resource waste.

For more details, please search " " on WeChat前端爱好者 and click me to view .

How to deal with anti-shake and throttling

Debouncing and throttling are two common optimization techniques used to prevent functions from being called excessively.

Anti-shake

For anti-shake , it can be processed in the following ways:

After the function is triggered, instead of executing the function immediately, set a delay time , such as n seconds.

If the function is triggered again within the delay time, the execution time is recalculated. The function is executed only if it is not triggered again within the delay time.

Throttle

For throttling, it can be handled in the following ways:

Also after the function is triggered, instead of executing the function immediately, set a time interval, such as executing the function every n seconds.

In this way, no matter how frequently the function is triggered, only the first trigger every n seconds will be executed.

For specific code to implement anti-shake and throttling, you can refer to the following sample code:

// 防抖
function debounce(fn, delay) {
    
      
  let timer = null;  
  return function() {
    
      
    clearTimeout(timer);  
    timer = setTimeout(() => {
    
      
      fn.apply(this, arguments);  
    }, delay);  
  };  
}

In the anti-shake function, we first define a timer variable timer.

When the function is triggered, first clear the last timer, then set a new timer, and execute function fn after a specified time delay.

This achieves the effect of executing the function only once within a period of time.

// 节流
function throttle(fn, delay) {
    
      
  let timer = null;  
  return function() {
    
      
    if (!timer) {
    
      
      timer = setTimeout(() => {
    
      
        fn.apply(this, arguments);  
        timer = null;  
      }, delay);  
    }  
  };  
}

In the throttling function, we also define a timer variable timer.

When the function is triggered, check whether the timer already exists. If it does not exist, set a new timer and execute the function fn after a delay of the specified time.

This achieves the effect of executing the function only once within a period of time.

Anti-shake example

For events triggered by frequent clicks or inputs in a short period of time, events that do not use anti-shake processing are not very good for the user experience. Therefore we can use anti-shake for processing, as follows:

<div class="box">
  进行防抖处理的:<input type="text" id="name" name="name">
</div>
<script>
  // 模仿一段ajax请求
  function ajax(value){
    
    
    console.log("ajax request: " + value + ", time: " + new Date());
  }
 
  // 防抖函数
  function debounce(func,delay){
    
    
    let timeout; //定时器
    return function(arguments){
    
    
      // 判断定时器是否存在,存在的话进行清除,重新进行定时器计数
      if(timeout) clearTimeout(timeout);//清除之前的事件
      timeout = setTimeout(()=>{
    
    
        func.call(this,arguments);//执行事件
      },delay);
    }
  }
 
  const inputBox = document.getElementById("name");
  // 使用防抖函数进行封装ajax
  let debounceAjax = debounce(ajax,500);
  inputBox.addEventListener("keyup",e=>{
    
    
    debounceAjax(e.target.value);
  })
</script>

As can be seen from the above running results, entering text and pressing the keyboard within 500ms will not trigger the request event. Instead, the request will be sent after the timer of the input box stops input for 500ms.

The implementation principle is very simple, which is to add a timer to count frequently input input box request events. Frequent input within the specified time will not make an ajax request, but the function will be executed only when input is stopped within the specified time interval.

When the input is stopped but within this timer counting time, the trigger request event will be retried.

Throttling example

<div class="box">
  进行节流处理的:<input type="text" id="name" name="name">
</div>
<script>
  // 模仿一段ajax请求
  function ajax(value){
    
    
    console.log("ajax request: " + value + ", time: " + new Date());
  }
 
  // 节流--定时器版
  function throttle(func,delay){
    
    
    let timeout;//定义一个定时器标记
    return function(arguments){
    
    
      // 判断是否存在定时器
      if(!timeout){
    
     
        // 创建一个定时器
        timeout = setTimeout(()=>{
    
    
          // delay时间间隔清空定时器
          clearTimeout(timeout);
          func.call(this,arguments);
        },delay)
      }
    }
  }
 
  const inputBox = document.getElementById("name");
  // 使用节流函数进行封装ajax
  let throttleAjax = throttle(ajax,500);
  inputBox.addEventListener("keyup",e=>{
    
    
    throttleAjax(e.target.value);
  })
</script>

As you can see from the above, no matter how much text we enter in the input box, the function will only be executed once within the specified time.

Vue + Axios global interface anti-shake, throttling encapsulation implementation

import axios from 'axios'

function request(config) {
    
    
    const instance = axios.create({
    
    
        baseURL: 'http://localhost:3000/api',
        timeout: 10000
    })

    // 防抖
    const debounceTokenCancel = new Map()
    instance.interceptors.request.use(config => {
    
    
    const tokenKey = `${
      
      config.method}-${
      
      config.url}`
    const cancel = debounceTokenCancel.get(tokenKey)
    if (cancel) {
    
    
        cancel()
    }
    return new Promise(resolve => {
    
    
        const timer = setTimeout(() => {
    
    
            clearTimeout(timer)
            resolve(config)
        }, 800)
        debounceTokenCancel.set(tokenKey, () => {
    
    
            clearTimeout(timer)
            resolve(new Error('取消请求'))
        })
      })
    }, error => {
    
    
        console.log(error)
        return Promise.reject(error)
    })

    instance.interceptors.response.use(response => {
    
    
        return response
    }, error => {
    
    
        console.log(error)
        return Promise.reject(error)
    })

    // 节流
    let lastTime = new Date().getTime()
    instance.interceptors.request.use(config => {
    
    
        const nowTime = new Date().getTime()
        if (nowTime - lastTime < 1000) {
    
    
            return Promise.reject(new Error('节流处理中,稍后再试'))
        }
        lastTime = nowTime
        return config
    }, error => {
    
    
        console.log(error)
        return Promise.reject(error)
    })

    return instance(config)
}

export default request

summary

  • Function anti-shake and function throttling both prevent frequent triggering within a certain period of time.
  • Function anti-shake is executed only once at a specified time, while function throttling is executed once at a specified interval.
  • Function anti-shake combines several operations into one operation, and function throttling causes the function to be triggered only once within a certain period of time.

Reference link

  • https://blog.csdn.net/qq_40716795/article/details/123144385
  • https://juejin.cn/post/7225133152490160187

Guess you like

Origin blog.csdn.net/BradenHan/article/details/134916740
Recommended