how to capture private variable

On running this code ( in nodejs), the 'Count' runs negative for large value of 'count'. Who is the culprit, 'count' or 'chain' ? What is the right way to write the 'flood' function, so that it schedules next invocation after a 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 i = 0 ; i < par ; i ++ ) {
        flood(count)
    }
}

runit(3,4)

Thanx

Update: If i call chain() instead of setTimeout(chain,1), the Count never goes negative.

chain is a global, since you have not used the var keyword. That makes your code behave like so, for runit(3, 4).

4 times:

flood(2); // Prints "Count 2" and calls setTimeout

Then the first round of asynchonous callback occurs. In that round chain was passed while it referred to the correct function so you will have another round using the correct chain and print "Count 1" four times, but on this round when you call setTimout you pass in the chain from the most recent call to flood, so now you have 4 asynchronous calls that single Chain and you'll get:

"Count 0"
"Count -1"
"Count -2"
"Count -3"

Declare it using var and your problem will be solved:

var chain = function() { ...