The first thing this code does is to execute this function (thanks to the ()
at the very end of the code you posted):
function() {
// SET TIMER
var timer = 0;
// RETURN SET TIMEOUT FUNCTION
return function(callback, ms) {
clearTimeout(timer);
timer = setTimeout(callback, ms);
};
}
and store the result in delay
. When executed, this function creates a closure with the local variable timer
that severs as a local counter. The function then returns the inner function:
function(callback, ms) {
clearTimeout(timer);
timer = setTimeout(callback, ms);
}
Since it is in closure, this inner function has access to the timer
variable. No other outside code can access timer
. This method is used to allow multiple timers to be running at once without having to worry about multiple timer
variables.
Imagine it like this: delay
now contains a function (function(callback, ms) {...
) which has access to a local variable, timer
. The variable timer
is invisible as far as any outside code is concerned. Only the function that delay
contains can access it.
You then invoke that inner function by calling delay(callback, timeout)
.