/**
* 防抖函数(常用于input框搜索情况)
* @param {*} func
* @param {*} delay
* @param {*} immediate
* @returns
*/
export function debounce(func, delay, immediate = true) {
let timer = null
return function(args) {
let _this = this
if (timer) clearTimeout(timer)
if (immediate) {
let now = !timer
timer = setTimeout(() => {
timer = null
}, delay)
now && func.call(_this, args)
} else {
timer = setTimeout(() => {
func.call(_this, args)
}, delay)
}
}
}
/**
* 节流函数(常用于onresize, onmouseover情况)
* @param {*} func
* @param {*} delay
* @param {*} immediate
* @returns
*/
export function throttle(func, delay, immediate = true) {
let timer
return function(args) {
let _this = this
if (immediate) {
let now = Date.now()
let prev = 0
if (now - prev > delay) {
func.call(_this, args)
prev = now
}
} else {
if (!timer) {
timer = setTimeout(() => {
timer = null
func.call(_this, args)
}, delay)
}
}
}
}
|