1. What is anti-shake
When the event is triggered, the wait time is recalculated. That is to say, the last code is triggered consecutivelywithin a unit of time
See Debounce at Lodash
/* * @func callback function * @wait number Specifies the time to wait for the function to trigger. The default value is 0 * @options Specifies the time to wait for the function to trigger. Forget that * @return returns a function */
lodash.debounce(func, [wait=0], [options=])
Copy the code
The simplest anti-shake function (no arguments)
function debonce(func,wait=0){
let timeId = null
return funciton (){
if(timeId){
clearTimeout(timeId)
}
timeId = setTimeout(func,awit)
}
}
Copy the code
Consider function passing parameters
function debonce(func,wait=0){
let timeId = null
return funciton (){
if(timeId){
clearTimeout(timeId)
}
timeId = setTimeout(() = >{
func.apply(this.arguments)
},wait)
}
}
Copy the code