function debounce(func, wait) {
var lastCallTime // 最后点击时的时间
var lastThis // 作用域
var timerId // 定时器
// 开启定时器
function startTimer(wait) {
return setTimeout(timerExpired, wait)
}
function remainingWait(time) {
const timeSinceLastCall = time - lastCallTime
const timeWaiting = wait - timeSinceLastCall
return timeWaiting
}
// 判断是否可以调用函数
function shouldInvoke(time) {
return lastCallTime !== undefined && (time - lastCallTime >= wait)
}
// 判断是否执行func
function timerExpired() {
const time = Date.now()
if (shouldInvoke(time)) {
return invokeFun()
}
timerId = startTimer(remainingWait(time))
}
// 调用func
function invokeFun() {
// clearTimeout(timeId)
timerId = undefined
const thisArg = lastThis
let result = func.call(thisArg)
lastThis = undefined
return result
}
function debounced() {
lastCallTime = Date.now()
lastThis = this
if (timerId === undefined) {
timerId = startTimer(wait)
}
}
return debounced
}
window.addEventListener(
'click',
debounce(function(event) {
var p = document.createElement('p')
p.innerHTML = 'trigger'
document.body.appendChild(p)
return 'aaaa'
}, 500)
)
console