将多次执行变为最后一次执行
- immediate:
- true:立即执行
- false:延迟执行
- 返回值:immediate为true时返回执行结果
- 可以取消延迟
function debounce(func, wait, immediate) {
var timeout
var result
var debounced = function () {
var context = this;
var args = arguments
if (timeout) clearTimeout(timeout)
if (immediate) {
var 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
}