JS节流实现-支持多个函数同时调用

JS节流说明:

限制一个函数在一定时间内只能执行一次

之前有关于JS防抖函数的实现,可以见JS防抖函数支持多个函数调用

本文采用的是时间戳结合定时器方式进行节流,且可以同时支持多个函数的调用

说明:md5_hex方式是md5算法对数据进行hash,可以自行下载https://download.csdn.net/download/u010899138/12614308

throttle函数

立即执行,适用于页面进入后立即加载数据,在wait时间内,fun的调用不会再执行

调用示例

// 默认执行后,在1500毫秒内再次执行只会输出一次throttle
CommonUtil.throttle(
  () => {
    console.log('throttle')
  }
)
// 第二次调用,只会有一个throttle执行
CommonUtil.throttle(
  () => {
    console.log('throttle')
  }
)

函数实现

/**
 * 说明:md5_hex函数是对函数体进行md5编码,作为key记录在map中,后续在移除fun时进行比对,
 * 在使用的时候,可以自行实现hash,也可以忽略,直接使用函数体的string作为key
*/
import {md5_hex} from './md5.js'
interface ParamsMap {
  startTime: number,
  wait: number,
}

class _CommonUtil {

  functionReqMap: Map<string, ParamsMap> = new Map()

  /**
   * 防抖函数(调用会立即触发,在wait时间内不再触发)
   * @param fun  业务函数
   * @param wait  等待时间(在等待时间内防止重复触发,默认1.5秒内拒绝所有数据)
   * 使用示例:wait可以不填写,默认1500毫秒
   * CommonUtil.throttle(()=>{
   *     // todo
   * },500)
   */
  throttle(fun: Function, wait: number = 1500) {
    let funcValue1 = fun.toString()
    let hash = md5_hex(funcValue1)
    let startTime = Date.now()
    if (this.functionReqMap.get(hash)) {
      let funcValue = this.functionReqMap.get(hash)
      // 防止因为特殊原因没有移除map中该函数的记录,导致一直无法执行函数的问题
      if (funcValue && funcValue.startTime + funcValue.wait <= startTime) {
        this.functionReqMap.delete(hash)
      } else {
        return
      }
    }
    this.functionReqMap.set(hash, {
      startTime: startTime,
      wait: wait,
    })
    // 执行函数调用
    fun()
    // 拦截在wait期间的函数再次调用,在超时后,将限制解除
    setTimeout(() => {
      let needRemoveKeys: string[] = []
      this.functionReqMap.forEach(((value, key, map) => {
        let curTime = Date.now()
        let funcValue = map.get(key)
        if (funcValue && funcValue.startTime + funcValue.wait <= curTime) {
          // @ts-ignore
          needRemoveKeys.push(key)
        }
      }))
      needRemoveKeys.map((value) => {
        this.functionReqMap.delete(value)
      })
    }, wait)
  }
}


export const CommonUtil = new _CommonUtil()

猜你喜欢

转载自blog.csdn.net/u010899138/article/details/107353791
今日推荐