节流
const throttle = (fn, time)=>{
// 一开始进入页面需要记录时间
let lasttime = 0
return ()=>{
// 记录滚动时的时间
let now = new Date().getTime()
if(now - lasttime > time){
fn.call(this)
lasttime = now
}
}
}
// 获取页面滚动
function roll(){
console.log('页面滚动');
}
window.onscroll = throttle(roll, 500)
防抖
function roll(){
console.log('页面滚动');
}
window.onscroll = debounce(roll, 500)
// 防抖函数
function debounce(cb, delay = 300){
let t = null
return function(){
clearTimeout(t)
t = setTimeout(() => {
cb.call(this)
}, delay);
}
}