前端笔试题 节流防抖的含义及代码
2022-10-11 本文已影响0人
江火渔枫
节流 节流指的都是某个函数在一定时间间隔内只执行第一次回调。
const throttle = (cb, wait=3000) => {
let timeId;
return (...args) => {
if( timeId ) return;
timeId = setTimeout(() => {
cb.apply(this, args);
timeId = undefined;
}, wait)
}
}
防抖 无视短时间内重复回调,限流是在某段时间内只执行首次回调,而防抖动通常是只执行末次回调。
function debounce(cb, wait = 3000) {
let timer = null
return (...args) => {
if (timer) clearTimeout(timer)
timer = setTimeout(() => {
timer = null;
cb.apply(this, args)
}, wait)
}
}