If you're using Node.js, you may consider using child_process to make asynchronous function calls which you can kill it later in case it doesn't finish in a period of time.
But this approach will need you to separate function x
to another JS file, say modulex.js which implements:
function x(){
// do whatever
}
x();
While, in your main.js (or any name you give it) where you want to start running function x
in that modulex.js asynchronously and kill it later, you call it via child_process which is one of the built-in feature of Node.js:
var spawn = require('child_process').spawn;
var x = spawn('node modulex.js'); // give any particular arguments if required
x.stdout.on('data', function (data) {
// event handler when function x finishes!
// data = any output printed by modulex.js
});
x.stderr.on('data', function (data) {
// event handler when function x fails!
// data = any error printed by modulex.js
});
// Or kill the `x` after a timeout with this:
function timeout(){
x.kill();
}
This approach will need you to redesign the architecture of your node application slightly. But this will cope with single-threaded JavaScript more efficiently.
I recommend reading this official documentation of child_process on node.js before getting started: https://nodejs.org/api/child_process.html