前端节流实现

节流(Throttling)是一种限制函数执行频率的技术,确保函数在指定的时间间隔内最多只执行一次,无论触发了多少次事件。这在处理像滚动、窗口调整大小、鼠标移动等频繁触发的事件时非常有用。

以下是实现节流的几种方法:

1. 使用lodash库的throttle函数

lodash提供了throttle函数来实现节流功能。

// 引入lodash的throttle函数
import _ from 'lodash';

// 创建一个节流函数
const throttledFunction = _.throttle(function() {
  // 这里是你的接口请求逻辑
  console.log('接口请求被触发');
}, 1000); // 1000毫秒的延迟时间

// 使用节流函数
window.addEventListener('resize', throttledFunction);

2. 手动实现throttle函数

如果你不想引入额外的库,可以自己实现一个throttle函数:

function throttle(func, limit) {
  let inThrottle;
  return function() {
    const args = arguments;
    const context = this;
    if (!inThrottle) {
      func.apply(context, args);
      inThrottle = true;
      setTimeout(() => (inThrottle = false), limit);
    }
  };
}

// 使用节流函数
const myThrottledFunction = throttle(function() {
  console.log('接口请求被触发');
}, 1000);

window.addEventListener('resize', myThrottledFunction);

3. 使用时间戳实现节流

这种方法确保在每个时间间隔的开始时执行一次函数。

function throttleByTimestamp(func, limit) {
  let lastFunc;
  let lastRan;
  return function() {
    const context = this;
    const args = arguments;
    if (!lastRan) {
      func.apply(context, args);
      lastRan = Date.now();
    } else {
      clearTimeout(lastFunc);
      lastFunc = setTimeout(function() {
        if ((Date.now() - lastRan) >= limit) {
          func.apply(context, args);
          lastRan = Date.now();
        }
      }, limit - (Date.now() - lastRan));
    }
  };
}

// 使用节流函数
const myThrottledFunctionTimestamp = throttleByTimestamp(function() {
  console.log('接口请求被触发');
}, 1000);

window.addEventListener('resize', myThrottledFunctionTimestamp);

4. 使用requestAnimationFrame实现节流

对于某些场景,如窗口调整大小或滚动事件,可以使用requestAnimationFrame来实现节流:

function throttleRAF(func, limit) {
  let frame;
  let lastFunc;
  let lastRan;
  return function() {
    const context = this;
    const args = arguments;
    if (!lastRan) {
      func.apply(context, args);
      lastRan = Date.now();
    } else {
      clearTimeout(lastFunc);
      if ((Date.now() - lastRan) >= limit) {
        func.apply(context, args);
        lastRan = Date.now();
      } else {
        frame = requestAnimationFrame(() => {
          if ((Date.now() - lastRan) >= limit) {
            func.apply(context, args);
            lastRan = Date.now();
          }
        });
      }
    }
  };
}

// 使用节流函数
const myThrottledFunctionRAF = throttleRAF(function() {
  console.log('接口请求被触发');
}, 1000);

window.addEventListener('resize', myThrottledFunctionRAF);

选择哪种方法取决于你的具体需求和场景。lodashthrottle函数是最简单直接的方法,而手动实现可以给你更多的控制权。对于需要高性能的场景,requestAnimationFrame可能是一个更好的选择。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值