I am trying to understand the mechanism of underscore.js debounce function: http://underscorejs.org/#debounce
Here is its native code:
_.debounce = function(func, wait, immediate) {
var timeout, args, context, timestamp, result;
var later = function() {
var last = _.now() - timestamp;
if (last < wait && last > 0) {
timeout = setTimeout(later, wait - last);
} else {
timeout = null;
if (!immediate) {
result = func.apply(context, args);
if (!timeout) context = args = null;
}
}
};
return function() {
context = this;
args = arguments;
timestamp = _.now();
var callNow = immediate && !timeout;
if (!timeout) timeout = setTimeout(later, wait);
if (callNow) {
result = func.apply(context, args);
context = args = null;
}
return result;
};
};
The thing I got stuck with is the context variable used in the inner returnable function. I can not understand why we should use it here and what context it contains. I tried to use the same function with the simple call of debounced function without applying any context to it and it also worked well. Here is my small fiddle with these two functions: http://jsfiddle.net/vlrt/fby9dhe0/11/
So, is the context necessary here? What context is needed to be applied?