防抖
回调事件在触发一段时间后才执行,在这段时间内多次触发则重新记时。
const debounce = function(fn, wait) {
let timer = null;
return function() {
const context = this, args = arguments;
// 触发时已经有记时器,则清空计时器,重新记时
if (timer) {
clearTimeout(timer);
timer = null;
}
timer = setTimeout(() => {
fn.apply(context, args)
}, wait)
}
}
需要注意箭头函数本身没有this,arguments,因此return的函数不能使用箭头函数。
节流
在一段时间内触发多次,只执行一次回调
const throttle = (fn, delay) => {
let preTime = Date.now();
return function() {
let context = this,
args = arguments,
nowTime = Date.now();
if (nowTime - preTime > delay) {
preTime = Date.now();
fn.apply(context, args);
}
}
}

本文介绍了JavaScript中防抖和节流两种优化事件处理的方法。防抖确保回调事件仅在最后一次触发后的一段时间内执行一次;节流则限制了回调在特定时间段内的执行频率。
605

被折叠的 条评论
为什么被折叠?



