当前位置:网站首页>js中性能优化之函数节流
js中性能优化之函数节流
2022-06-09 17:47:00 【前端三脚猫】
定义
限制在规定时间内只触发一次函数执行,将多余的触发给忽略掉。
也可以直接理解节流就是节省流量(代码执行开销),将原本高频率的操作降低到我们设置的时间频率内执行。
适用场景
从定义可知节流主要是降低函数执行的频率,节省执行开销的同时并且不耽误正常的功能实现,所以它所适用的大多数就是那种触发频率极高的场景,如果我们不做处理并且触发的函数里面有一些开销比较大的操作(如大量操作dom或者进行ajax请求等)可能会造成浏览器性能阻塞造成卡顿。例如:
1、 浏览器窗口变化事件 window.onresize
浏览器窗口的大小在改变的时候onresize 事件触发的频率非常高.
2、 mousemove事件
当我们绑定了拖拽事件,进行拖拽的时候该事件同样也会被频繁的触发。
3、 scroll事件
窗口的滚动事件当进行滚动的时候也会被频繁的触发。
实现原理
从上述可知导致问题的原因就是因为函数被触发的频率太高导致,做了需要不必要的操作,所以我们只需要人为的将触发的频率降低到合适的频率即可。例如在拖拽事件进行的时候,想要进行发起请求可能一秒钟发一次或者两次就足以实现功能,那么我们就可以根据时间忽略掉其他不必要的请求。
代码实现
于函数节流的代码实现有许多种,下面将使用setTimeout 定时器延迟一段时间执行来实现。具体代码如下:
/**
*
* @param {*} callback 需要执行的函数
* @param {*} time 函数执行的间隔
*
*/
const saveTraffic = (callback, time) => {
let timer,
firstTime;
return function(...res) {
const _this = this;
// 第一次调用直接执行即可
if (firstTime) {
callback.apply(_this, res);
return firstTime = false;
};
if (timer) return;
timer = setTimeout(() => {
clearTimeout(timer);
timer = null;
callback.apply(_this, res);
}, time || 500)
}
}
上述代码中将即将被执行的函数用 setTimeout 定时器延迟一段时间执行,如果该次延迟执行还没有完成,则忽略接下来调用该函数的触发。
测试
window.onresize = saveTraffic(function(res) {
console.log(1111, res)
}, 300);
边栏推荐
- NLP - 关键词提取 - TextRank
- Android 缓存机制 LRUCache
- Abbexa DUT ELISA 试剂盒测定原理
- Operation manual of abbexa PCR super mixture
- Moco -Momentum Contrast for Unsupervised Visual Representation Learning
- 谷歌浏览器书签保存在哪里以及书签导入导出方法
- Active prevention DWS key tool installation confirmation
- Redis knowledge points & summary of interview questions
- Influence of K value selection in KNN on Model
- Abbexa 质粒 MiniPrep 试剂盒检测程序
猜你喜欢

CREMB Pro 后台子管理员 403 问题分析

Solve the chrome prompt: "your connection is not a private connection" and there is no continue access option

导电滑环的主要应用在那些方面

谷歌浏览器书签保存在哪里以及书签导入导出方法

Why do SQL statements use indexes but still slow queries?

ARM指令集复习 | 基本指令用法

go-zero 微服务实战系列(二、服务拆分)

音频 3A 处理实践,让你的应用更「动听」

Influence of two residual structures on NLP networks

Operation manual of abbexa PCR super mixture
随机推荐
[typecho]如何进行多表查询
Oracle分页
C语言选举人投票功能
sqllite create a database
Who says redis can't save big keys
ARM指令集复习 | 基本指令用法
How about opening an account with tongdaxin? Is it safe to open an account?
Solve the chrome prompt: "your connection is not a private connection" and there is no continue access option
Running the code, I want to add a progress bar to see the running progress of the following code in real time. How can I break it?
What are the main applications of conductive slip rings
为什么 SQL 语句使用了索引,但却还是慢查询?
C language to solve the problem of climbing stairs
How to realize face verification quickly and accurately?
AI首席架构师3-AICA-智慧城市中的AI应用实践
音频 3A 处理实践,让你的应用更「动听」
【工作随笔记】Tina 系统的 ADB、声卡、网卡、串口多路共存
性能优化方案
OpenCV中的带参数宏定义CV_Assert()的作用
Redis knowledge points & summary of interview questions
CPU program interrupt