Debounce means that when a function is fired, it will not execute until the time we set is up, and if it is fired several times before the set time, the timer will be reset until the last time the function is triggered has passed the set time.
The general application scenario is: the input component makes some requests according to the user’s input, such as the demand for associative words. At this time, we try not to request every time the change event of the input is triggered. We can wait for the user to stop input, such as 100ms to request.
Specific scenarios can be based on the actual function of this function and then combined with business requirements to consider whether to use.
Let’s see how:
function debounce(fn, delay) {
let timer
return function(. args) {
if (timer) clearTimeout(timer)
// Use the arrow function to handle this problem
timer = setTimeout((a)= > fn.apply(this, args), delay)
}
}
Copy the code
In this way, a basic version of the anti – shake function is written.
Then we can optimize it. In practice, we might want to make it execute immediately the first time and then delay it later. How do we do this?
function debounce(fn, delay, immediate) {
let timer
let result
return function(. args) {
if (timer) clearTimeout(timer)
if (immediate) {
// If the timer exists, it means that the delay time is not reached when the second call is made, because if the delay time is exceeded
// The timer will be assigned to null, so we should not execute fn at this time, we should reset a timer
// If the timer is set once, it will be undefined because no timer has been set
if (timer) {
timer = setTimeout((a)= > timer = null, delay)
} else {
result = fn.apply(this, args)
return result
}
} else {
timer = setTimeout((a)= > fn.apply(this, args), delay)
}
}
}
Copy the code
A practical implementation like Lodash. Debounce would be a little more complicated than that, because there are so many cases to consider, but the basic idea is there.