一、防抖
function debounce (func, wait, immediate) {
let timeout, result
let debounced = function () {
let context = this
let args = arguments
clearTimeout(timeout)
if(immediate) {
let callNow = !timeout
timeout = setTimeout(function () {
timeout = null
}, wait)
if(callNow) result = func.apply(context, args)
} else {
timeout = setTimeout(function () {
func.apply(context, args)
}, wait)
}
return result
}
debounced.cancel = function () {
clearTimeout(timeout)
timeout = null
}
return debounced
}
二、节流
function throttle (func, wait, options) {
let timeout, context, args, result
let previous = 0
if(!options) options = {}
let later = function () {
previous = options.leading === false ? 0 : +new Date()
timeout = null
func.apply(context, args)
if(!timeout) context = args = null
}
let throttled = function () {
let now = +new Date()
if(!previous && options.leading === false) previous = now
context = this
args = arguments
let remaining = wait - (now - previous)
if(remaining <= 0 || remaining > wait) {
if(timeout) {
clearTimeout(timeout)
timeout = null
}
previous = now
func.apply(context, args)
if(!timeout) context = args = null
} else if (!timeout && options.trailing !== false) {
timeout = setTimeout(later, remaining)
}
}
throttled.cancel = function () {
clearTimeout(timeout)
previous = 0
timeout = null
}
return throttled
}
参考:https://github.com/mqyqingfeng/Blog/issues/26