Open zxdfe opened 1 year ago
防抖debounce:持续触发事件时,在一定的时间内没有再触发事件,则执行回调函数,如果在设定的时间内再次触发事件,则重新计算延迟
const debounce = function (fn, ms) {
let timerId
return function () {
clearInterval(timerId)
timerId = setTimeout(() => {
fn.call(this)
},ms)
} // end return
} // end debounce
节流throttle:持续触发事件时,在一段时间内只执行一次回调函数
const throttle = function (fn, ms) {
let startTime = 0
return function () {
let now = +new Date()
if (now - startTime >= ms) {
fn.call(this)
startTime = +new Date()
}
} // end return
} // end throttle
防抖debounce:在一定时间的间隔内, 将多次触发变成一次触发;相当于LOL里面英雄按B回城,在回城途中动了再按B回城得重新计时;应用于搜索栏,节省性能,限制鼠标连续点击按钮提交; 节流throttle:持续的触发事件,在一段时间内只允许函数触发一次;相当于英雄的技能,每个技能都有cd事件,一定时间只能触发一次;懒加载监听滚动条的位置,或者resize事件; 能手写debounce,很熟练,throttle不熟练,不想敲了...