// 非立即执行版,及n秒内时间执行一次函数, 如果n秒又触发了事件,则会重新计算时间
function debounce (func, wait) {
let timer
return function (){
let context = this
let args = arguments
if (timer) clearTimeout(timer)
timer = setTimeout(() => {
func.apply(context, args)
}, wait)
}
}
// 立即执行版,触发事件后函数立即执行,在n秒内不触发事件,才能继续执行函数的效果
function debounce2 (func, wait) {
let timer
return function (){
let context = this
let args = arguments
if (timer) clearTimeout(timer)
let flag = !timer
timer = setTimeout(() => {
timer = null
}, wait)
if (flag) func.apply(context, args)
}
}
// 组合判断,根据业务场景情况选择使用
function debounce3 (func, wait, immediate) {
let timer
return function() {
let context = this
let args = arguments
if (timer) clearTimeout(timer)
// 如果需要立即执行
if (immediate) {
let flag = !timer
timer = setTimeout(() => {
timer = null
}, wait)
if (flag) func.apply(context, args)
} else {
timer = setTimeout(() => {
func.apply(context, args)
}, wait)
}
}
}
// 节流。 时间戳版
function throttle(func, wait) {
let previous = 0
return function() {
let now = Date.now()
let context = this
let args = arguments
// 立即执行一次,之后n秒再执行
if (now - previous > wait) {
func.apply(context, args)
previous = now
}
}
}
// 定时器版。在持续触发事件的过程中,函数不会立即执行,并且每 1s 执行一次,在停止触发事件后,函数还会再执行一次
function throttle2(func, wait) {
let timer
return function() {
let context = this
let args = arguments
if (!timer) {
timer = setTimeout(() => {
timer = null
func.apply(func, wait)
},wait)
}
}
}
网友评论