Hi in this code block my requirement is to execute the function test() such that it should stop executing ( it was going through an infinite loop and crashing the page) if it takes for than 1 min.
I used promise and timer to solve this issue but here the problem i am facing is timeout function is being called even before executeWithRace was executed and it is not working as expected, How to refactor this code?
async function executeWithRace() {
const response = await Promise.race([timeoutPromise, testPromise]);
console.log(response)
}
const timeoutPromise = new Promise((resolve, reject) => {
setTimeout(() => {
resolve('Timed Out');
}, 60000); // 1 minute timeout
});
const testPromise = new Promise((resolve, reject) => {
test(); // Execute the original test function
resolve("testSuccessfull"); // Resolve if test function completes without error
});
Thanks
I also tried to create functions for both of the promises and passed those functions to promise.race() but here I have faced this situation : only the first mentioned function in promise.race() was being executed and both the functions weren’t being executed simultaneously.
Sourabh Raja is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.
0
JS is single threaded so your “infinite loop” function blocks everything else completely. You cannot solve that with async or setTimeout (they are blocked too). You could try a worker and worker.terminate() for scenarios like that.
3