let btn = document.getElementById("btn")
const click = function() {
console.log('click')
}
// 函数的防抖(在一段时间内连续触发只执行最后一次,常见于input框搜索)
const shake = function(fn, delay) {
let timer = null;
return (...arg) => {
clearInterval(timer);
timer = setTimeout(() =>{
fn.call(this, arg)
}, delay)
}
}
// 函数的节流(防止多次触发,常见于上拉加载更多等)
const throttle = function(fn, wait) {
let prevTime = 0;
return (...arg) => {
let nowTime = Date.now();
if(nowTime - prevTime > wait) {
fn.call(this, arg);
prevTime = nowTime
}
}
}
btn.addEventListener('click', throttle(click, 2000));
节流与防抖
最新推荐文章于 2024-02-20 15:31:13 发布