Skip to content Skip to sidebar Skip to footer

NodeJs: Cancel Function Call If It Takes Too Long

In my Node.js app I need some sort of mechanism to stop a function call if it takes too long. function testIt() { ... } runFunctionOnlyFor(1000, testIt, function (err) { if (e

Solution 1:

I see some issues here.

1) You normally shouldn't write blocking code in Node.JS, even if it's "only" 1 second. If this is a web service with many clients, blocking for one second could have devastating performance effects.

2) Since Node.JS is effectively single-threaded I don't really see any easy way to cancel the execution after a certain amount of time unless the time-keeping is done by testit itself, since you would need a separate thread to run the function that aborts the function running in the first thread.

A better approach is likely to make the testit function async, and break it down into several steps with intermediate context switches, and periodically check for a flag or similar that may be set by runFunctionOnlyFor once a timer for the desired duration expires.

Another way is to use a child process , if that suits your purposes.


Post a Comment for "NodeJs: Cancel Function Call If It Takes Too Long"