防抖 节流
...小于 1 分钟
https://flowus.cn/375ce54a-3804-4d56-8580-f1abf9afde14
思维导图


代码
//防抖函数
//_this 是 接收原函数this
//...args 是 剩余参数
//核心功能:开启定时器记录id,在代码前面清除定时器
export function debounce(fn, delay = 0) {
let timeId = null
return function (...args) {
let _this = this
if (timeId) clearTimeout(timeId)
timeId = setTimeout(function () {
fn.apply(_this, args)
}, delay)
}
}//节流函数
export function throttle(fn, delay = 0) {
let timeId = null
return function (...args) {
let _this = this
//如果不存在定时器
if (!timeId) {
timeId = setTimeout(function () {
fn.apply(_this, args)
timeId = null
}, delay)
}
}
}
export function throttle(fn, delay = 0) {
let timeId = null
return function (...args) {
let _this = this
//如果不存在定时器
if (timeId) return;
timeId = setTimeout(function () {
fn.apply(_this, args)
timeId = null
}, delay)
}
} 赞助





