Reputation: 2673
I am looking at the Leaflet api.
Is there a reason why in setTimeout, it is calling wrapperFn.apply(context, args);
and not fn.apply(context, args);
?
I tried it out, and it gives me the same output. But wondering if there a significance to it ?
function a(fn, time, context) { var lock, execOnUnlock; return function wrapperFn() { var args = arguments; if (lock) { execOnUnlock = true; return; } lock = true; setTimeout(function () { lock = false; if (execOnUnlock) { wrapperFn.apply(context, args); execOnUnlock = false; } }, time); fn.apply(context, args); }; },
Upvotes: 3
Views: 115
Reputation: 700302
The function creates a wrapper for the function that is the first parameter, which can only be executed at an interval specified by the second parameter. If you call it again one or more times inside the interval, the last of those calls will be executed automatically after the interval.
var f = a(someFunction, 1000, {});
f(1); // this will execute the function
f(2); // this will not be executed
f(3); // this will be executed after a second
setTimeout(function(){
f(4); // this will be executed a half second later (two seconds after the first)
}, 1500);
The call that is made automatically at the end of the interval will lock the function for another time interval. If the code would call fn
instead of wrapperFn
, then that call would not be locked, and you could call the function again inside the interval. Example:
var f = a(someFunction, 1000, {});
f(1); // this will execute the function
f(2); // this will not be executed
f(3); // this will be executed after a second
setTimeout(function(){
f(4); // this would be executed immediately (1.5 seconds after the first)
}, 1500);
Upvotes: 2