throttle
- 时间戳方法, 首次会立马执行, 之后隔 N 秒执行一次
js
export function throttle(fn, wait) {
let previous = 0
return function (...args) {
let now = new Date().valueOf()
if (now - previous >= wait) {
fn.call(this, ...args)
previous = now
}
}
}鼠标放下去试试, 每隔 1 秒数字加 1
0
- 定时函数方法, 首次不会马上执行, N 秒后才会执行, 停止触发后 N 秒还会执行一次
js
export function throttle(fn, wait) {
let timer
return function (...args) {
if (!timer) {
timer = setTimeout(() => {
fn.call(this, ...args)
timer = null
}, wait)
}
}
}鼠标放下去试试, 每隔 1 秒数字加 1
0
- 双剑合璧: 首次立马执行, 之后隔 N 秒执行一次,停止触发后 N 秒还会执行一次
js
export function throttle(fn, wait) {
let previous = 0
let timer
return function (...args) {
const now = new Date().valueOf()
const remaining = wait - (now - previous)
if (remaining <= 0 || remaining > wait) {
if (timer) {
clearTimeout(timer)
timer = null
}
previous = now
fn.apply(this, args)
} else {
if (!timer) {
timer = setTimeout(() => {
previous = new Date().valueOf()
timer = null
fn.apply(this, args)
}, remaining)
}
}
}
}鼠标放下去试试, 每隔 1 秒数字加 1
0