closures - Understanding throttle in javascript the correct way -
hi i'm trying understand throttling in javascript. have 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 test using 2 different functions callback
function x() { console.log('timeout x'); } function y() { console.log('timeout y'); }
now here questions: calling runonce(x);runonce(x);runonce(x);
multiple times, throttle function seems ok (only invoke function x 1 time)
- but why "console.log('no hurry please');" never invoked?
when call runonce(x);runonce(x);runonce(y);runonce(y);
function x , function y called 1 time, good.
- but why if call
runonce(x);runonce(y);runonce(x);runonce(y);
, both function x , function y called 2 times?
thanks
the problem in runonce code. solved if move var active outside of function (thanks @andreas link). , repair function bit. following full code work:
var active, fnarray = []; function runonce(fn, ms) { if (typeof(fn) !== "function") return; ms = ms || 5000; return (function() { if (active && fnarray.indexof(fn.name) >= 0) { console.log('no hurry please'); } else { fnarray.push(fn.name); active = settimeout(function() { fnarray = fnarray.filter(function(elm) { elm !== fn.name }); fn(); }, ms); } })(); }; function x() { document.body.innerhtml += 'timeout x </br>'; } function y() { document.body.innerhtml += 'timeout y </br>'; } runonce(x); runonce(x); runonce(x); runonce(y); runonce(x); runonce(y);
Comments
Post a Comment