节流、防抖函数(TypeScript)

1、节流函数

节流(throttling)函数是一种在特定时间内只允许某个函数执行一次的技术。它可以用于限制函数执行的频率,例如在滚动、窗口调整大小、鼠标移动等高频事件中使用,避免函数被过多调用,导致性能问题。

定时器实现节流

/** 
* @param func { T } => 节流的函数
* @param limit { number } => 节流时间(毫秒)
*/
function throttle<T extends (...args: any[]) => void>(func: T, limit: number): T {
  let inThrottle: boolean;

  return function(this: ThisParameterType<T>, ...args: Parameters<T>) {
    const context = this;

    if (!inThrottle) {
      func.apply(context, args);
      inThrottle = true;
      setTimeout(() => inThrottle = false, limit);
    }
  } as T;
}

时间戳实现节流

/** 
* @param func { T } => 节流的函数
* @param limit { number } => 节流时间(毫秒)
*/
function throttle<T extends (...args: any[]) => void>(func: T, limit: number): T {
  let lastFunc: ReturnType<typeof setTimeout>;
  let lastRan: number;

  return function(this: ThisParameterType<T>, ...args: Parameters<T>) {
    const context = this;

    if (!lastRan) {
      func.apply(context, args);
      lastRan = Date.now();
    } else {
      clearTimeout(lastFunc);
      lastFunc = setTimeout(() => {
        if ((Date.now() - lastRan) >= limit) {
          func.apply(context, args);
          lastRan = Date.now();
        }
      }, limit - (Date.now() - lastRan));
    }
  } as T;
}

使用方法

// 需节流的函数
function func () {
	console.log("123123123......")
}
window.addEventListener('scroll', throttle(func, 1000);


2、防抖函数

防抖(debounce)函数是一种在事件触发后,等待一段时间,如果在等待期间事件再次被触发,则重新开始计时,直到等待时间结束才执行函数。这可以避免在短时间内多次触发同一个事件时多次执行相应的处理函数。

/** 
* @param func { T } => 防抖的函数
* @param wait { number } => 防抖时间(毫秒)
*/
function debounce<T extends (...args: any[]) => any>(func: T, wait: number): T {
  let timeout: ReturnType<typeof setTimeout>;

  return function(this: ThisParameterType<T>, ...args: Parameters<T>) {
    const context = this;

    clearTimeout(timeout);
    timeout = setTimeout(() => func.apply(context, args), wait);
  } as T;
}

使用方法

// 防抖函数
const func = debounce(() => {
	console.log("123123123......")
}, 1000)

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值