Package of anti-shake and throttling tools

1. Overview of anti-shake and throttling

For anti-shake, it means that the function is executed n seconds after the event is triggered. If the event is triggered again within n seconds, the function execution time will be recalculated. The specific effect is that if we trigger the event frequently , the execution of the function will always be delayed , and the function will be executed once n seconds after the last trigger event.

For throttling, the function is executed at most once in n seconds, regardless of the frequency of the trigger event. The specific effect is that if we continue to trigger the event at a high frequency, the execution frequency of the function will be close to once every n seconds.

2. Tool class encapsulation

The anti-shake class and throttling class codes are as follows:
The use of the class is very simple. In the construction method, the event processing function and the time interval value are passed in to generate an anti-shake or throttling object, and the excute( ) method, the event processing function will be automatically executed in the way of anti-shake or throttling.

// 防抖
export class Debounce{
    
    
  private timeout:number
  private task:() => void
  private setTimeoutId:any = 0
  constructor(task:() => void, timeDelay:number){
    
    
    this.setTimeoutId
    this.task = task
    this.timeout = timeDelay
  }
  public excute(){
    
    
    clearTimeout(this.setTimeoutId)
    this.setTimeoutId = setTimeout(() => {
    
    
      this.task()
    }, this.timeout);
  }
}

// 节流
export class Throttle{
    
    
  private timeout:number
  private task:() => void
  private setTimeoutId:any = 0
  private ok = true //是否执行
  constructor(task:() => void, timeDelay:number){
    
    
    this.setTimeoutId
    this.task = task
    this.timeout = timeDelay
  }
  public excute(){
    
    
    if(this.ok){
    
    
      this.task()
      this.ok = false
      setTimeout(() => {
    
    
        this.ok = true
      }, this.timeout);
    }
  }
}

3. Example of use

3.1 Number increase, anti-shake and throttling

Renderings:
insert image description here

The vue template code is as follows:

<template>
  <div>
    <div>
      数字:{
   
   { num }}
    </div>
    <button @click="debounceAdd.excute()">防抖,数字加一</button>
    <button @click="throttleAdd.excute()">节流,数字加一</button>
  </div>
</template>

The ts code is as follows:

<script setup lang="ts">
import {
    
     ref } from '@vue/reactivity'
import {
    
    Debounce, Throttle} from '../../util/excuteFunc'
const num = ref(1)
const debounceAdd = new Debounce(add, 1000)
const throttleAdd = new Throttle(add, 1000)
function add(){
    
    
  num.value++
}
</script>

3.2 Listening to resize events, anti-shake

Monitor the change of the browser window. If the window size does not change again within one second after the window size changes, execute the code that handles the window size change.

Code without anti-shake:

window.onresize = function(e){
    
    
  console.log('窗口大小发生了变化,resize事件对象为:')
  console.log(e)
}

Code to use anti-shake:

let debounceResizeHandler:Debounce
window.onresize = function(e){
    
    
  if(!debounceResizeHandler){
    
    
  	//如果还未初始化防抖对象,则初始化防抖对象
    debounceResizeHandler = new Debounce(() => {
    
    
      // 处理窗口大小变化的代码
      console.log('窗口大小发生了变化,resize事件对象为:')
      console.log(e)
    }, 1000)
  }
  debounceResizeHandler.excute()
}

Mainstream anti-shake throttling writing

The above method of returning anti-shake and throttling objects seems to be rare. At present, what everyone likes to use is to return a function of anti-shake and throttling.

export function ToDebounce(fn:Function, timeout:number){
    
    
  let id = 0
  return function(...args:any[]){
    
    
    clearTimeout(id)
    id = setTimeout(() => {
    
    
      fn(...args)
    }, timeout);
  }
}

export function ToThrottle(fn:Function, timeout:number, ...args:any[]){
    
    
  let id = 0
  let excute = true // 是否可以执行函数
  return function(...args:any[]){
    
    
    if(excute){
    
    
      fn(...args)
      excute = false
      setTimeout(() => {
    
    
        excute = true
      }, timeout);
    }
  }
}

Guess you like

Origin blog.csdn.net/m0_52744273/article/details/128841852