There are a lot of anti โ throttling codes on nuggets, I was also read a star to learn the most. I didnโt pay much attention to the rest, but as a result, what he wrote was wrong. If I didnโt react quickly and really understand the principle during the interview, I would be ruined by him
. Anyway, feel quite deceiving, send blog, if canโt do accurate words that share out is not harm people? The most SAO is his that article dot like number
is the most, you dare to believe? (That shows how many people he screwedโฆ) Without further ado, go to the code
I will explain the idea of two methods, remember to grasp the idea!
Ps: There is nothing wrong with the anti-shake in that article, there is something wrong with throttling.
code
/ / image stabilization
// Thought: each trigger, reset timer
function debounce(func, timer){
let hasTime = null
return (. args) = > {
// The essence of anti-shock is the following line of code
reset timer
clearTimeout(hasTime)
hasTime = setTimeout((a)= >{
func.call(this. args) }, timer) } }// Be sure to write test code and run around the console
var a = (a)= >{console.log('aaa')}
var b = debounce(a,2000)
b()
b()
...
Copy the code
/ / throttling
// Thought: after each execution, the timer can be reset
function throttle(func, timer){
let bool = false
return (. args) = > {
if(bool) return
bool = true
setTimeout((a)= >{
func.call(this. args)// The point is that the next one can only be done
bool = false
},timer)
}
}
// Be sure to write test code and run around the console
var a = (a)= >{console.log('aaa')}
var b = throttle(a,2000)
b()
b()
...
Copy the code
Below is the source of LoDash, well loDash throttling using anti โ shake implementation. Because loDashโs anti-shake feature is very powerful. You can control method execution at the beginning or end of timing
Source line too many, I this is a shortened version, the full version of my stamp
/ / lodash stabilization
function debounced(. args) {
const time = Date.now()
const isInvoking = shouldInvoke(time)
lastArgs = args
lastThis = this
lastCallTime = time
if (isInvoking) {
if (timerId === undefined) {
return leadingEdge(lastCallTime)
}
if (maxing) {
// Handle invocations in a tight loop.
timerId = startTimer(timerExpired, wait)
return invokeFunc(lastCallTime)
}
}
if (timerId === undefined) {
timerId = startTimer(timerExpired, wait)
}
return result
}
Copy the code
// The Lodash section has two parameters for anti-shaking
function throttle(func, wait, options) {
let leading = true
let trailing = true
if (typeoffunc ! = ='function') {
throw new TypeError('Expected a function')}if (isObject(options)) {
leading = 'leading' inoptions ? !!!!! options.leading : leading trailing ='trailing' inoptions ? !!!!! options.trailing : trailing }//
is called
return debounce(func, wait, {
leading,
trailing,
'maxWait': wait
})
}
Copy the code
conclusion
Know is know, noknow is noknow, is also know.
See the article must oneself begin an experiment! A fall into the pit, a gain in your wit