On the debounce principle of

function debounce (fn, delay) {

var timer

return function () {


var context = this
var args = arguments


clearTimeout(timer)



timer = setTimeout(function () {
  fn.apply(context, args)
}, delay)

}
}

The

code does not understand why it is necessary to add a layer of return function here

solve

Apr.03,2021

1. debounce is a high-order function that takes a function as an argument and returns a function that is anti-shake wrapped. So what is returned must be a function.

2. As for why the original function is not returned directly, it is because the anti-shake processing needs to judge the jitter before the original function is executed, and the content of the original function cannot be modified, so you need to return a self-defined function to execute the judgment logic

.

var s=debounce (fn,args);
.
s ()

call

at the appropriate time after generating the function.

closure. Otherwise, timer will be new every time, and you won't be able to remember the timer on the previous one.

that means your clearTimeout (timer) is equivalent to clearTimeout (undefined)

Menu