当前位置:网站首页>防抖和节流有什么区别,分别用于什么场景?
防抖和节流有什么区别,分别用于什么场景?
2022-07-30 18:40:00 【小萌新入场】

防抖
防抖:单位时间内多次点击,以最后一次为准。
形象的描述:王者里的回城,只要被打断就需要重新来(单位时间内,多次触发,且以最后一次为准)
例如:一个搜索输入框,用户不停的进行输入(这个时候就是抖动的过程),等用户输入停止之后,再触发搜索。
代码演示
function debounce(fn, delay = 200) {
let timer = 0
return function() {
// 如果这个函数已经被触发了
if(timer){
clearTimeout(timer)
}
timer = setTimeout(() => {
fn.apply(this, arguments); // 透传 this和参数
timer = 0
},delay)
}
}
节流
节流:单位时间内只触发一次,以第一次为准。
形象的描述下:想象一下王者荣耀的平a;或者技能CD冷却时间也好理解(单位时间内,只能触发一次,且以第一次为准)
例如:王者游戏里的英雄,你一个劲的使劲平a,会发现每次平a 过后都要短暂的停留一下,这就可以做到节流。
回归正题:drag(拖动)事件或者 scroll(滚动) 期间触发某个回调,要设置一个时间间隔。这时候就不能使用防抖了,为什么呢?
防抖是拖拽或者滚动结束之后才返回回调,但是我是需要在过程中进行触发回调,但是又不需要那么的频繁;这时候就使用节流函数,每隔一定的时间进行触发就好了!
代码演示
// 节流函数
function throttle(fn, delay = 200) {
let timer = 0
return function () {
if(timer){
return
}
timer = setTimeout(() =>{
fn.apply(this, arguments); // 透传 this和参数
timer = 0
},delay)
}
}
你可能会发现,防抖函数、节流函数很相似?
区别仅在于:
防抖:
if(timer){
clearTimeout(timer)
}
节流:
if(timer){
return
}
他们在定时器已经有任务的时候,操作不同。
防抖函数在每一次都有内容后进行清除,是为了保证当前执行的函数就是(当前规定的时间内)执行的最后一次操作
if(timer){
clearTimeout(timer)
}
节流函数如此操作是为了保证,在规定的时间内只会执行第一次这个操作
if(timer){
return
}
总结
遇到防抖,就想起王者荣耀里的 回城;
遇到节流,就想起王者荣耀里的 平a、技能cd冷却时间;

边栏推荐
猜你喜欢

C# wpf 无边框窗口添加阴影效果

Meta元宇宙部门第二季度亏损28亿!仍要继续押注?元宇宙发展尚未看到出路!

One year after graduation, I was engaged in software testing and won 11.5k. I didn't lose face to the post-98 generation...

攻防世界web-Cat

kotlin by lazy

SwiftUI iOS Boutique Open Source Project Complete Baked Food Recipe App based on SQLite (tutorial including source code)

【Swords Offer】Swords Offer 17. Print n digits from 1 to the largest

NC | 西湖大学陶亮组-TMPRSS2“助攻”病毒感染并介导索氏梭菌出血毒素的宿主入侵...

Codeblocks + Widgets 创建窗口代码分析

运营 23 年,昔日“国内第一大电商网站”黄了...
随机推荐
【剑指 Offe】剑指 Offer 17. 打印从1到最大的n位数
Immersive experience iFLYTEK 2022 Consumer Expo "Official Designated Product"
OSPF详解(3)
The use of @ symbol in MySql
CCNA-ACL(访问控制列表)标准ACL 扩展ACL 命名ACL
原生js系列
好未来单季营收2.24亿美元:同比降84% 张邦鑫持股26.3%
微信小程序云开发 | 城市信息管理
CIMC Shilian Dafeitong is the global industrial artificial intelligence AI leader, the world's top AI core technology, high generalization, high robustness, sparse sample continuous learning, industri
常见链表题及其 Go 实现
DM8: Single database and single instance to build a local data guard service
Swiper轮播图片并播放背景音乐
node封装一个控制台进度条插件
【PHPWord】PHPOffice 套件之PHPWord快速入门
Node encapsulates a console progress bar plugin
What is the value of biomedical papers? How to translate the papers into Chinese and English?
Mysql执行原理剖析
攻防世界web-Cat
[Use of Qt Designer tool]
【Swords Offer】Swords Offer 17. Print n digits from 1 to the largest