节流
// 节流就是「技能冷却中」
const throttle = (fn, time) => {
let 冷却中 = false
return (...args) => {
if(冷却中) return
fn.call(undefined, ...args)
冷却中 = true
setTimeout(()=>{
冷却中 = false
}, time)}
}
// 还有一个版本是在冷却结束时调用 fn
// 简洁版,删掉冷却中变量,直接使用 timer 代替
const throttle = (f, time) => {
let timer = null
return (...args) => {
if(timer) {return}
f.call(undefined, ...args)
timer = setTimeout(()=>{
timer = null
}, time)}
}
防抖
function debounce(fn, time) {
//定义一个定时器,保存上一次定时器
let timerCool
return function (...args) { //真真执行的函数
//取消上一次定时
if (timerCool) clearTimeout(timerCool)
//延迟执行
timerCool = setTimeout(() => {
//外部传入的真真要执行的函数
fn.apply(this, args)
}, time)
}
}
总结
为了方便自己后期查看而总结,大佬就不用看啦. 哈哈哈勿喷.