Anti-shake function

export function debounce(func, wait, immediate) {
let timeout, args, context, timestamp, result

const later = function() {
// According to the last trigger time interval
const last = +new Date() - timestamp

// last time the function is called package is less than the last time interval set time interval wait
if (last < wait && last > 0) {
timeout = setTimeout(later, wait - last)
} else {
timeout = null
// If set to immediate === true, since the beginning of the border has been called up here without calling
if (!immediate) {
result = func.apply(context, args)
if (!timeout) context = args = null
}
}
}

return function(...args) {
context = this
timestamp = +new Date()
const callNow = immediate && !timeout
// If there is no delay, reset delay
if (!timeout) timeout = setTimeout(later, wait)
if (callNow) {
result = func.apply(context, args)
context = args = null
}

return result
}
}

Guess you like

Origin www.cnblogs.com/binglove/p/11419642.html