hi I'm trying to understand Throttling in javascript. I have this code
function runOnce(fn, ms) {
if(typeOf(fn) !== "function")
return;
ms = ms || 5000;
var active;
return (function() {
if(active) {
console.log('no hurry please');
} else {
active = setTimeout(fn, ms);
}
})();
};
I want to test using two different functions callback
function x() {
console.log('timeout from x');
}
function y() {
console.log('timeout from y');
}
Now here are my questions:
Calling runOnce(x);runOnce(x);runOnce(x);
multiple times, the throttle function seems ok (only invoke function x one time)
- but why the "console.log('no hurry please');" never get invoked?
when i call runOnce(x);runOnce(x);runOnce(y);runOnce(y);
the function x and function y only be called 1 time, that is good.
- but why if i call
runOnce(x);runOnce(y);runOnce(x);runOnce(y);
, both function x and function y are called 2 times?
thanks