Coder3000
Coder3000

Reputation: 130

Node setTimeout notWorking

function work(){
    //do some of the heavy computation now
    process.nextTick(work);
}

work();


console.log("started");
setTimeout(function(){ console.log("hi there");}, 1000);

When I run his code I get : started, but I never get the message hi there. Am I doing something wrong, or is this an issue with node?

Edit: When I replace the process.nextTick with setTimeout it works, but nextTick is supposed to be faster, or when I replace setTimeout with process.nextTick() hello shows but it doesn't wait 1000ms.

Upvotes: 2

Views: 401

Answers (2)

Jaromanda X
Jaromanda X

Reputation: 1

using setImmediate is the way to go

function work(){
    setImmediate(work);
}

work();


console.log("started");
setTimeout(function(){ console.log("hi there");}, 1000);

Upvotes: 1

piemonkey
piemonkey

Reputation: 751

Node.js works with an event loop, (simplistically speaking) it will run any code until it returns and then run the next thing in its queue. process.nextTick() sets the function you pass it to be the next thing in that queue. setTimeout(foo, x) will tell it to add the function you pass to the queue in x milliseconds.

Your code is adding work as the next thing in the queue then finishing, so then node runs the work function, which does something then adds work as the next thing in the queue, this continues forever. At some point the timer ends and it adds your log to the queue, but since nextTick is always adding work as the first thing in the queue, it never actually pick it up.

Upvotes: 0

Related Questions