I am currently looking for a way to timeout on a synchonous JavaScript code using node.
In a nutshell: I have a synchronous code which takes too long (for instance: an infinite loop). I would be interesting in stopping its run.
On async function
I found a way to do it on asynchronous calls using Promise.race with a custom delay promise which ends after Xxx milliseconds.
For asynchronous functions the code is the following:
function timeoutIt(fun, timeMs) {
return Promise.race([
fun(),
new Promise((resolve, reject) => setTimeout(reject, timeMs))
]);
}
I tried to derive this snippet to receive my synchronous function, but once the function has been called the reject Promise is never executed. Any idea to have some kind of timeout on synchronous code?
Context: I am currently working on a property based testing framework https://github.com/dubzzz/fast-check and wanted to be able to work even for disruptive cases where the code goes into infinite loops. For the moment, the code holds and wait for the test framework to timeout on its side
Thanks in advance for your help