节流和防抖,相信很多学习前端的人都听过,也都学过,但是有时候需要一段时间去理解,为啥呢,因为这是英语翻译过来的啊,中国人谁能直接理解这个词对吧。
但是,身为一个程序员或者宅男,魔兽、DOTA、英雄联盟、星际总玩过一个吧,里面的技能跟回城/读条总知道吧,那我今天用英雄联盟做例子来记录一下节流防抖的大致概念。
节流「技能冷却中」
玩英雄联盟的谁没用过闪现对吧。
点击闪现后,是不是就有CD?
CD期间再用闪现,是不是就没用了?
节流跟这个概念其实是有点类似的:
const sx = () => {
console.log('闪现')
}
let 冷却中 = false // 默认没进入冷却
let timer = null // 定时器默认为空
function onClickSx() { // 点击闪现
if (冷却中) { return } // 如果闪现在冷却,就返回,没有在冷却则执行 闪现 并进入冷却
sx()
冷却中 = true // 闪现后进入冷却,此时点击闪现没有反应
timer = setTimeout(() => { // 120 秒之后冷却结束
冷却中 = false
}, 120 * 1000)
}
这就是节流,只是肯定不是符合标准的节流写法, 只是为了理解概念。
那么如何写出符合任何需求的节流呢?
写一个函数,用来实现任何技能都可以进入冷却:
const sx = (distance) => { // 闪现接收一个距离 distance
console.log('闪现')
}
const throttle = (skill, time) => {
let timer = null // 是否冷却中
return (...args) => {
if (timer) { return } // 有在冷却 就返回
skill.call(undefined, ...args) // 没有 this 的情况
timer = setTimeout(() => {
timer = null // 冷却时间到后,再把时间置为空
}, time)
}
}
const sx2 = throttle(sx, 120 * 1000)
再把这段代码修改成符合代码写法的节流:
const throttle = (fn, time) => {
let timer = null
return (...args) => {
if (timer) { return }
fn.call(undefined, ...args)
timer = setTimeout(() => {
timer = null
}, time)
}
}
这就是通过技能冷却原理修修改改得来的节流代码,至少我个人理解起来方便很多。
接下来说一下防抖:
防抖 「回城被打断」
刚刚交完闪现杀完人,现在身上一堆钱,准备回城,但是被小兵攻击了,所以回城被打断了,需要重新回城。
const f = () => {
console.log('回城成功')
}
let timer = null // 回城计时,默认为空
function x() {
if (timer) { // 如果正在回城,打断回城将会重新计时(不为 null 时,则 timer 存在)
clearTimeout(timer)
}
timer = setTimeout(() => {
fn()
timer = null // 回城成功后,再置为空
}, 3000)
}
// 你只要打断我,我就重新回城;3秒钟之内你又一次打断我,我又重新回城
那写一个满足防抖需求的:写一个通用的函数,任何功能都可以实现打断了之后再重新计时。
标准写法:
const debounce = (fn, time) => {
let timer = null
return (...args) => {
if (timer != null) {
clearTimeout(timer)
}
timer = setTimeout(() => {
fn.call(undefined, ...args)
timer = null
}, time)
}
}
以上就是我对节流防抖的理解以及在网上找资料得来的总结笔记,那么节流防抖一般会在什么场景使用呢?
节流
一般只在不希望用户频繁点击按钮的时候使用节流。
防抖
当用户进行一个频繁拖动操作的时候,我希望在拖动停止之后再去实现一个效果。