节流
一个函数执行一次后,只有大于设定的执行周期后才会执行第二次。 有个需要频繁触发函数,出于优化性能角度,在规定时间内,只让函数触发的第一次生效,后面不生效。
实现
// 时间戳 立即执行
function throttle(func, awit) {
let old = 0
return function () {
const that = this
const args = arguments
let now = newDate().valueOf()
if (now - old > wait) {
func.apply(that, func)
old = now
}
}
}
// 使用定时器 第一次不执行,最后一次调用会执行
function throttle(func, wait) {
let timeout
return function () {
const that = this
const args = arguments
if (!timeout) {
timeout = setTimeout(function () {
func.apply(that, args)
timeout = null
}, wait)
}
}
}
大约 2 分钟