* 节流:在指定的时间间隔内,函数只被调用一次
* 定时器版 - 节流:会delay的时间后,才执行一次
设置一个定时器,在指定的时间间隔内不再触发事件
如果在指定的时间间隔内再次触发了事件,则不执行函数,直到定时器到期后再次执行函数。
const throttle = (fn, delay) => {
let timerId
return (...args) => {
const _this = this
if (!timerId) {
timerId = setTimeout(() => {
fn.apply(_this, args)
timerId = null
}, delay)
}
}
}
-------------------------------------------------------------------------
* 时间戳版 - 节流:适合处理一些 `需要立即响应` 的事件
在事件触发后,记录下当前的时间戳,并在下次事件触发时再次记录时间戳,
在指定的时间间隔内,如果事件再次触发,则更新时间戳,
如果时间戳与当前时间的差值超过了指定的时间间隔,则执行函数。
function throttle(fn, delay) {
let last = 0
return (...args) => {
const _this = this
const now = +new Date()
// console.log('now=', now) // now就是个时间戳
if (now - last > delay) {
fn.apply(_this, args)
last = now
}
}
}
function logFlag() {
console.log(123)
}
// 使用节流
// 注意:页面加载完后,无论滚动条滚不滚动,都会默认执行一次scroll事件
document.querySelector('.divDom').addEventListener('scroll', throttle(logFlag, 3000))
// 不使用节流
// document.querySelector('.divDom').addEventListener('scroll', logFlag)
js -节流
最新推荐文章于 2024-05-31 10:26:40 发布