I am trying to make a timeout function that throws an error in case a function hangs for too long.
I have the following code:
function go() {
try{
console.log('started, timeout in 2 seconds...');
setTimeout(()=>{
throw new Error('Timed Out!');
}, 2000);
while(true){
//will run forever
}
}catch (e) {
console.log('timeout function worked!');
}
}
go();
However, the error is never thrown. I think this is because of how the event loop works in JS, but I'd like for my timeout function to execute after 2 seconds regardless of what else is happening. How do I achieve this?