Js 防抖与节流
Js 防抖与节流
function showTop() {
var scrollTop = document.body.scrollTop || document.documentElement.scrollTop;
console.log('滚动条位置:' + scrollTop);
}
window.onscroll = showTop
// 滚动一下会执行 n次
防抖
/*
* fn [function] 需要防抖的函数
* delay [number] 毫秒,防抖期限值
*/
function debounce(fn, delay) {
let timer = null; // 定义空变量
return function () {
if (timer) {
clearTimeout(timer);
// 说明当前正在计时,并且又触发了相同事件,所以清除当前计时器。
}
timer = setTimeout(fn, delay); // 反之则启动。
}
}
// 结合滚动函数
window.onscroll = debounce(showTop, 1000)
节流
function throttle(fn, delay) {
let flag = true
return function () {
if (!flag) {
// 关
return false
}
// 开,执行函数并且在间隔期内把状态位设为无效
flag = false
setTimeout(() => {
fn()
flag = true;
}, delay)
}
}
// 结合滚动函数
window.onscroll = throttle(showTop, 1000)
中括号法可以用数字作为属性名,而点语法不可以。