Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

In Node.js, If i am writing a long running function should I be using setTimeout

or something else to queue up the rest of my function? and use callbacks or does node handle that automatically?

I imagine that I would need to start my code and if there are other things that need to occur I should be giving up my functions control to give other events control. Is this the case? Or can i be stingy and node will cut off my function when I have used enough time?

Thanks.

like image 473
MrUnleaded Avatar asked Feb 24 '23 06:02

MrUnleaded


1 Answers

If your long-running function does a lot of I/O just make sure that you do this in a non-blocking way. This is how node.js achieves concurrency even though it only has a single thread: As soon as any task needs to wait for something, another task gets the CPU.

If your long-running function needs uninterrupted CPU time (or the I/O cannot be made asynchronously) , then you probably need to fork out a separate process, because otherwise every one else will have to wait until you are done.

Or can i be stingy and node will cut off my function when I have used enough time?

No. This is totally cooperative multi-tasking. Node cannot preempt you.

like image 153
Thilo Avatar answered Feb 26 '23 21:02

Thilo