下面给你最常用、最标准、直接可复制的防抖 & 节流实现,附带使用示例,一看就会。
原理:频繁触发时,只在最后一次触发后延迟执行,中间全部忽略。
function debounce(fn, delay = 300) {
let timer = null;
return function (...args) {
clearTimeout(timer);
timer = setTimeout(() => {
fn.apply(this, args);
}, delay);
};
}const onSearch = debounce((value) => {
console.log("请求搜索:", value);
}, 500);
input.addEventListener("input", (e) => {
onSearch(e.target.value);
});原理:固定时间内只执行一次,不管触发多频繁。
function throttle(fn, interval = 300) {
let lastTime = 0;
return function (...args) {
const now = Date.now();
if (now - lastTime >= interval) {
fn.apply(this, args);
lastTime = now;
}
};
}const handleScroll = throttle(() => {
console.log("滚动位置", window.scrollY);
}, 300);
window.addEventListener("scroll", handleScroll);有些场景希望第一次立即执行,后面再防抖:
function debounceImmediate(fn, delay = 300) {
let timer = null;
return function (...args) {
const isFirst = !timer;
clearTimeout(timer);
timer = setTimeout(() => {
timer = null;
}, delay);
if (isFirst) {
fn.apply(this, args);
}
};
}需要我给你写一个带取消功能、支持立即执行、兼容 React 的高级版防抖节流吗?
原创声明:本文系作者授权腾讯云开发者社区发表,未经许可,不得转载。
如有侵权,请联系 cloudcommunity@tencent.com 删除。
原创声明:本文系作者授权腾讯云开发者社区发表,未经许可,不得转载。
如有侵权,请联系 cloudcommunity@tencent.com 删除。