With this debounce function:
function debounce(fn, delay) {
var timer
return function () {
var context = this
var args = arguments
clearTimeout(timer)
timer = setTimeout(function () {
fn.apply(context, args)
}, delay)
}
}
can someone explain why I should use fn.apply(context,args) instead of fn() only?
I know .apply will change the context and var context = this will make the context always be the same as the context in fn(). I can't find a scenario where using fn() and fn.apply(context, args) gives a different result.
Can someone give me an example?
Consider the following class:
So what gets logged, and when, and how many times? You are going to see one value logged, one time, about half a second after the last call. With the definition you posted you'll see
a. If you omit the contextual part you'll seeundefined: