Necesito establecer un tiempo máximo para una función en Javascript para que la función se detenga automáticamente después de un cierto tiempo si aún no ha terminado. ¿Alguna solución para hacerlo?
function foo() { // foo() execute user script and it should stop after few seconds if the user did something wrong (like infinite loop) to avoid browser crash }Puede intentar ejecutar su función en modo asíncrono, para poder controlarla con promesas:
const foo = () => { let a = 1; while (a < 10000) a++; return 'Result ' + a; } const timeoutFunc = async (func, timeout = 0, errorResult = 'ERR')=>{ let timeoutHandle; let mainHandle; const timeoutPromise = new Promise((resolve) => { timeoutHandle = setTimeout( () => { resolve(errorResult) }, timeout ); }); const asyncPromise = new Promise((resolve) => { mainHandle = setTimeout( () => { resolve(func()) }, ); }); return Promise.race([asyncPromise, timeoutPromise]).then(result => { clearTimeout(mainHandle); clearTimeout(timeoutHandle); return result; }) } const tryToCallFunction = async (timeout)=>{ const res = await timeoutFunc(foo, timeout); console.log('FINAL RESULT: ', res) } tryToCallFunction(1); // this show timeout Error result tryToCallFunction(11); // this show the correct result