javascript - how to capture private variable -


on running code ( in nodejs), 'count' runs negative large value of 'count'. culprit, 'count' or 'chain' ? right way write 'flood' function, schedules next invocation after settimeout().

flood =  function( count) {         chain = function() {         --count;         console.log("count " + count)         if( count > 0 ) {             settimeout(chain, 1);         }     };     chain(); }   runit = function (count,par) {     console.log("runit: " + count + " , " + par )     for( var = 0 ; < par ; ++ ) {         flood(count)     } }  runit(3,4) 

thanx

update: if call chain() instead of settimeout(chain,1), count never goes negative.

chain global, since have not used var keyword. makes code behave so, runit(3, 4).

4 times:

flood(2); // prints "count 2" , calls settimeout 

then first round of asynchonous callback occurs. in round chain passed while referred correct function have round using correct chain , print "count 1" 4 times, on round when call settimout pass in chain recent call flood, have 4 asynchronous calls single chain , you'll get:

"count 0" "count -1" "count -2" "count -3" 

declare using var , problem solved:

var chain = function() { ... 

Comments

Popular posts from this blog

php - Calling a template part from a post -

Firefox SVG shape not printing when it has stroke -

How to mention the localhost in android -