时间戳
缺点: 第一次直接触发 最后一次1000ms内无法触发
function throttle(fun, delay) {
let pre = Date.now()
return function () {
if (Date.now() - pre > 1000) {
fun(delay, arguments)
pre = Date.now()
}
}
}
function handle() {
console.log('throttle')
}
window.addEventListener('scroll', throttle(handle, 1000))
定时器
缺点: 第一次延迟触发 最后一次延迟触发
function throttle(fn, delay) {
let timer = null
return function () {
if (!timer) {
timer = setTimeout(() => {
fn.apply(this, arguments)
timer = null
}, delay)
}
}
}
function handle() {
console.log('throttle')
}
window.addEventListener('scroll', throttle(handle, 1000))
时间戳 + 定时器
优点: 第一次立即触发, 最后一次延迟触发
function throttle(fn, delay) {
let timer = null
let pre = Date.now()
return function () {
clearTimeout(timer)
let remain = delay - (Date.now() - pre)
if (remain < 0) {
fn.apply(this, arguments)
pre = Date.now()
} else {
timer = setTimeout(() => {
fn.apply(this, arguments)
}, remain)
}
}
}
function handle() {
console.log('throttle')
}
window.addEventListener('scroll', throttle(handle, 1000))