whitfin
whitfin

Reputation: 4639

NodeJS clearTimeout() doesn't seem to work correctly?

I have a timeout which basically kills the process after it's run for too long, however this is only if a certain condition hasn't been met by then. Should my condition be hit, I'm using clearTimeout() to clear the timeout, but it seems that the error and process kill persist.

Here is my code snippet; the error is still printed out after 5 minutes even if the clearTimeout() is hit.

function poll(callback){
    var timeLimit = setTimeout(function(){
        if(log) log("Could not get a response from the command.", "error");
        process.exit(1);
    }, 300000);
    exec("some command", function(error, stdout, stderr){
        if(stdout){
            clearTimeout(timeLimit);
            // Do other stuff
        } else {
            setTimeout(function(){
                poll(callback);
            }, 1000);
        }
    });
}

I tested in browser and it seemed to work in a typical JavaScript console, but perhaps I'm doing something wrong above?

If so, any help will be appreciated. The above is my exact code (aside from the command and error messages, of course) so if anything is wrong it should be visible above.

Thanks in advance.

Upvotes: 2

Views: 3766

Answers (1)

whitfin
whitfin

Reputation: 4639

Bleh, late night moment.

setTimeout() is inside the polling function so it's reset every time it polls, meaning I can't clear out the old instances. Move it outside of the function and it works just fine.

Upvotes: 2

Related Questions