Function image stabilization
Concept: An action is delayed for a period of time, and when triggered again within this period of time, the previous timer retry timer is cleared.
function debounce (fn, time=300) {
let timer // Cache a timer object
return function (. args) {
// If the timer object exists when triggered, the reset timer is cleared
timer && clearTimeout(timer)
timer = setTimeout(() = > {
fn.apply(this, args) // doSomething
timer = null
}, time)
}
}
Copy the code
Applicable scenario
- Button submission scenario: Prevents multiple button submissions and only performs the last submission
- Server validation scenario: Form validation requires server coordination, only a sequence of input events for the last time, and a similar function of searching for associative words
A function closure
Concept: Execute only once at a time
function throttle (fn, time=300) {
let flag
return function (. args) {
if (flag) return
flag = setTimeout(() = > {
fn.apply(this, args) // doSomething
flag = null
}, time)
}
}
Copy the code