- 防抖动,是将多次执行变为最后一次执行指定时间内只执行一次,但在等待时间内再次触发事件,重新开始延时。
- 节流,是将多次执行变成每隔一段时间执行。指定时间内只执行一次。
JavaScript函数防抖(debounce)
- 作用:防止用户短时间内,大量高频的重复点击按钮,导致大量触发请求
方法一:使用setTimeout延迟执行
function debounce(func, delay) {
let timeoutId;
return function() {
clearTimeout(timeoutId);
timeoutId = setTimeout(func, delay);
};
}
// 示例用法
const button = document.querySelector('button');
button.addEventListener('click', debounce(function() {
console.log('按钮被点击了!');
}, 2000));
方法二:使用时间戳进行判断
function debounce(func, delay) {
let lastTimestamp = 0;
return function() {
const now = Date.now();
if (now - lastTimestamp >= delay) {
func();
lastTimestamp = now;
}
};
}
// 示例用法
const button = document.querySelector('button');
button.addEventListener('click', debounce(function() {
console.log('按钮被点击了!');
}, 2000));
方法三:使用Lodash库
// 需要先安装Lodash库(npm install lodash)
const debounce = require('lodash.debounce');
// 示例用法
const button = document.querySelector('button');
button.addEventListener('click', debounce(function() {
console.log('按钮被点击了!');
}, 2000));
特殊情况:Vue3 使用setup语法糖时
const timerId = ref(null);
const buttonClick = () => {
clearTimeout(timerId.value);
timerId.value = setTimeout(() => {
console.log('按钮被点击了!');
}, 2000);
};
JavaScript节流(debounce)
let timer = null
function throttle (fn, delay = 300) {
if(timer == null){
timer = setTimeout(() => {
fn()
clearTimeout(timer)
timer = null
}, delay);
}
}
function buttonClick(){
throttle(()=>{
console.log('Button clicked!');
}, 2000)
}