dhrm
dhrm

Reputation: 14934

Node loop: Maximum call stack size exceeded

I'm trying to implement a infinite loop, doing some work every 5 second inspired by a single threaded HTTP monitor.

function doWork(callback) {
    console.log("doWork called");
    //todo: do work
    callback();
}

function query_doWork() {
    doWork(function() {
        setTimeout(query_doWork(), 5000);
    });
}

query_doWork();

Instead of printing "doWork called" every 5 second, it just flush a lot of this, and exit in this state:

RangeError: Maximum call stack size exceeded

Maybe I don't something fundamental about Node.js, but I get why this is not working properly. What is the reason?

Upvotes: 0

Views: 567

Answers (1)

JuniorCompressor
JuniorCompressor

Reputation: 20015

In setTimeout you should define what is the function you want to call. What you are doing instead, is calling it. That's why you enter in an infinite recursion loop. So replace:

setTimeout(query_doWork(), 5000);

with:

setTimeout(query_doWork, 5000);

Upvotes: 3

Related Questions