当前位置: 首页 > article >正文

前端节流实现

节流(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可能是一个更好的选择。


http://www.kler.cn/a/441990.html

相关文章:

  • OpenAI直播发布第8天:ChatGPT Search全面升级,免费开放!
  • AJAX 和 XML:现代 Web 开发的关键技术
  • Dubbo 3.x源码(26)—Dubbo服务引用源码(9)应用级服务发现订阅refreshServiceDiscoveryInvoker
  • 面试中常问的软件测试面试题
  • 概率论得学习和整理28:用EXCEL画折线图,X轴数据也被当成曲线的解决办法
  • 代码审计 | 如何获取CVE漏洞编号
  • xpath插件安装与使用
  • Java每日一题(1)
  • vue_shop项目
  • VMware虚拟机Ubuntu 18.04版本 磁盘扩容
  • Webpack学习笔记(1)
  • 【YashanDB知识库】kettle同步大表提示java内存溢出
  • Linux系统安全与应用: 筑牢防线,高效运维
  • 2012年西部数学奥林匹克试题(几何)
  • Linux服务器修改自己目录下的cuda版本
  • [蓝桥杯 2019 国 B] 排列数
  • 记录一次 ftp 安装 无法连接的问题
  • 视频孪生在景区文件场景中的应用
  • Unity A*算法实现+演示
  • clickhouse 分布式表创建、增加、更新、删除、查询