Onlife/common/jieliu/leets_debounced_throttle.ts
2025-04-19 15:38:48 +08:00

86 lines
2.6 KiB
TypeScript
Raw Permalink Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

// 使用方法:
// import { Throttle, Debounced } from "./lee_debounced_throttle"
// let a: Function = new Debounced().useFn(handleLogin, 3000) // New一个防抖对象
// let b: Function = new Throttle().useFn(handleLogin, 3000) // New一个节流对象
// function leeBouce() {
// a()
// b()
// }
/**
* 防抖类
*/
class Debounced {
/**
* 防抖函数
* 1、N秒内的多次触发仅执行最后一次
* 2、在不断的触发事件时以最后一次触发为*标准*准进行调用执行
* 3、判断连续触发事件的标准为(N秒内触发则重新计算时间直至取最后一次)
* @param fn 需要防抖处理的回调函数
* @param delay 防抖处理的延迟标准时间
* @param immediate 是否默认 立即执行(去除延迟时间影响)
*/
public useFn(fn: Function, delay: number = 1000, immediate: boolean = false): Function {
let timer: NodeJS.Timeout | undefined
return (...args: any) => {
if (immediate) {
console.log("立即执行参数 执行一次方法")
fn.apply(this, args)
immediate = false
return
}
if (timer) {
console.log("当前正在重复点击准备重置时间重新计算后等待N秒触发最后一次事件执行")
clearTimeout(timer)
}
timer = setTimeout(() => {
console.log("进入类启用定时器防抖执行了一次方法咯!!!")
clearTimeout(timer)
fn.apply(this, args)
}, delay)
}
}
}
/**
* 节流类
*/
class Throttle {
/**
* 节流函数
* N秒内仅执行第一次
* @param fn 需要节流处理的回调函数
* @param delay 节流处理的延迟标准时间
* @param immediate 是否默认 立即执行(去除延迟时间影响)
*/
public useFn(fn: Function, delay: number = 1000, immediate: boolean = false): Function {
console.log("进入节流对象")
let timer: NodeJS.Timeout | undefined
let status: boolean = false // 是否为重复点击状态
return (...args: any) => {
if (immediate) {
console.log("立即执行参数 执行一次方法")
fn.apply(this, args)
immediate = false
return
}
if (status) {
console.log("当前点击状态为正在重复点击,请稍等片刻后在点击执行")
return
}
console.log("执行节流:当前执行了一次点击方法")
fn.apply(this, args)
status = true // 修改状态
timer = setTimeout(() => {
console.log("规定时间到,重置状态,可以重新调用")
status = false
}, delay)
}
}
}
export {
Debounced,
Throttle
}