当前位置:网站首页>JS 封装节流(后期优化)
JS 封装节流(后期优化)
2022-08-09 11:25:00 【ik i5】
1 .认识节流throttle函数
节流的过程
- 当事件触发时,会执行这个事件的响应函数;
- 如果这个事件会被频繁触发,那么节流函数会按照一定的频率来执行函数;
- 不管在这个中间有多少次触发这个事件,执行函数的频繁总是固定的;
节流的应用场景:- 监听页面的滚动事件;
- 鼠标移动事件;
- 用户频繁点击按钮操作;
- 游戏中的一些设计;
游戏理解: 节流就是英雄CD
生活理解: 坐电梯时每一层的到达时间
2. Underscore实现节流
<!-- //第三方库使用防抖节流 -->
<input type="text">
<script src="https://cdn.jsdelivr.net/npm/[email protected]/underscore-umd-min.js"></script>
<script>
const inputEl = document.querySelector('input')
let count = 0
const inputChange = function (event) {
count++
console.log(`发送了我们的第${
count}次网络请求`, this,event);
}
// // 防抖只执行一次
// inputEl.οninput=_.debounce(inputChange,2000)
// 节流固定的时间进行触发
inputEl.oninput = _.throttle(inputChange, 2000)
3 手写节流
- 图解节流的实现
3. 1节流函数的基本实现
<!-- //第三方库使用防抖节流 -->
<input type="text">
<button id="cancel">取消</button>
<!-- <script src="https://cdn.jsdelivr.net/npm/[email protected]/underscore-umd-min.js"></script> -->
<script>
const inputEl = document.querySelector('input')
let count = 0
const inputChange = function (event) {
count++
console.log(`发送了我们的第${
count}次网络请求`, this, event);
}
// 节流固定的时间进行触发
inputEl.oninput = throttle(inputChange, 2000)
// 封装节流 :关键在于: 节流阀 以及时间间隔
function throttle(callback, times) {
let lastTime=0 //初始值
// 在接受这两个值时需要返回一个函数
const _throttle = function (...args) {
// 获取当前时间的秒数
const nowTime=new Date().getTime()
// 2-(无穷大-0)=-数 执行
// 2.2.使用当前触发的时间和之前的时间间隔以及上一次开始的时间, 计算出还剩余多长事件需要去触发函数
const remainTime= times-(nowTime- lastTime)
if (remainTime<=0) {
callback.call(this,args)
// 重新赋值后 times还是2s不调用callback节流阀函数
lastTime=nowTime //第二次执行的初始时间(保留上次触发的时间)
}
}
return _throttle
}
优化
<input type="text">
<button id="cancel">取消</button>
<!-- <script src="https://cdn.jsdelivr.net/npm/[email protected]/underscore-umd-min.js"></script> -->
<script>
const inputEl = document.querySelector('input')
let count = 0
const inputChange = function (event) {
count++
console.log(`发送了我们的第${
count}次网络请求`, this, event);
}
// 节流固定的时间进行触发
inputEl.oninput = throttle(inputChange, 2000)
// 封装节流 :关键在于: 节流阀 以及时间间隔
//1 如果不触发函数则节流阀关闭状态
// 当你触发这个函数时先把节流阀关闭 然后在默认的时间间隔中打开
function throttle(callback, delaytime) {
let state=true //节流阀打开
return function(){
if (!state) {
//当节流阀关闭,则直接退出该函数
return; //callback不执行
}else{
//如果节流阀打开先把节流阀关闭
//然后设置时间间隔后在自动打开
state = false
setTimeout(() => {
callback && callback()
state = true
}, delaytime)
}
}
}
</script>
后期优化
优化一:节流最后一次也可以执行
优化二:优化添加取消功能
优化三:优化返回值问题
边栏推荐
猜你喜欢
随机推荐
Oracle数据库的两种进入方式
学长告诉我,大厂MySQL都是通过SSH连接的
ACM01背包问题
es6递归函数
[现代控制理论]5_系统的可控性_controllability
CAN总线发送数据
x86异常处理与中断机制(1)概述中断的来源和处理方式
【Basic model】Transformer-实现中英翻译
redis缓存如何保证数据一致性
电解电容漏电流及均压
抗积分饱和 PID代码实现,matlab仿真实现
Open3D 点云平均点间距评估
OC-NSTimer
CentOS6.5 32bit安装Oracle-11gR2步骤说明
Semaphore SIGCHLD use, how to make the parent that the child performs over, how to make the distinction between multiple child processes. The end
富媒体在客服IM消息通信中的秒发实践
PAT1006
【VQA survey】视觉问答中的语言学问题
TIC2000调用API函数Flash擦除片上FLASH失败
PTA习题 分类统计字符个数(C)