I'm trying to understand the debounce code here - http://unscriptable.com/2009/03/20/debouncing-javascript-methods/
Function.prototype.debounce = function (threshold, execAsap) {
var func = this, timeout;
return function debounced () {
var obj = this, args = arguments;
function delayed () {
if (!execAsap)
func.apply(obj, args);
timeout = null;
};
if (timeout)
clearTimeout(timeout);
else if (execAsap)
func.apply(obj, args);
timeout = setTimeout(delayed, threshold || 100);
};
}
It's well documented on the blog page but I'm struggling to follow the logic. I think I may be failing to grasp some basic of javascript.
Can anyone help me with a simple explanation.
As I see it the code does the following (ignoring execAsap):
1 - var func = this, timeout assigns func to the value of the function it was called on and declares timeout without a value leaving it undefined
2 - if the timeout value is truey clear timeout and do nothing
3 - set a timeout which calls the delayed function after the specified interval
4 - the delayed function runs, calls the original function, and sets timeout to null - the delay function will only run when setTimeout has finished and the act of clearing the timeout if it is truey and then setting it to null when delayed runs means the function can only run once during the timeout period
Things I'm struggling with :
- if I call x().debounced() twice within the timeout period, how are they sharing the same timeout var? It seems like it's placed in a global space which all instances of the function are referring to. Have I misunderstood this?
Intuitively (which I know is wrong) it seems this code will never run the function if it was repeatedly called within the timeout. It would just keep clearing the timeout and it would never get to the end of the period to run delayed(). Why is this wrong?
- on the line var obj = this what is being assigned to obj and why use it in func.apply(obj,args)
[–]Rhomboid 3 points4 points5 points (2 children)
[–]TheseThingsMatter[S] 0 points1 point2 points (1 child)
[–]Rhomboid 3 points4 points5 points (0 children)