setTimeout to achieve asynchronicity in Node

What is the point of doing setTimeout(fx, 0) in node?

This is not asynchronous or even non-blocking, as the async function is really the setTimeout, not your fx, and after setTimeout has run asynchronously, you will end up running fx which will block your code anyway.

Doing the setTimeout with 0 to call a function fx will just wait until the stack is empty to run fx, but then while fx is running you won't be able to accept any requests, right?

So is setTimeout(fx, 0) just a way of telling node 'hey, run this whenever you can'? Is there any way to trully run async functions in Node?

Upvotes: 0

Views: 48

Answers (2)

noa-dev
noa-dev

Reputation: 3641

If I understand your question correctly the answer would be the following:

As JavaScript is a single threaded language it is still able to deal with two things separately.

Using setTimeout(fx, 0) allows you to push the function or operation within the setTimeout Function in a "waiting qeue". As soon as the Stack of operations is completed the function gets put onto the execution stack and gets executed.

More detailed information about that can be found in this video

Upvotes: 1

nikjohn
nikjohn

Reputation: 21850

If your question is:

Can node run functions in parallel at the same time?

Then the answer is yes, but you have to use a web worker.

The paradigm of asynchronosity in node is different from traditional definitions. The expectation is that you don't run too many ultra-long running functions in node. This way, effective asynchronosity is achieved.

Node is good for some things, not for others, just like any environment.

For a more detailed answer, refer here

As for setTimeout(...,0) calls; sometimes giving a break during a time consuming task to allow calls in the queue have their share of processing can be required. Dividing tasks in different ways can save you from these; but still, this is not really a hack, it is just the way event queues work. Also, using process.nextTick for this aim is much better since when you use setTimeout, calculation and checks of the time passed will be necessary while process.nextTick is simply what we really want: "Hey task, go back to end of the queue, you have used your share!"

Upvotes: 1

Related Questions