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)
}
function timerExpired() {
const time = Date.now()
if (shouldInvoke(time)) {
return invokeFun()
}
timerId = startTimer(remainingWait(time))
}
function invokeFun() {
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