Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

222
Views
Establecer el tiempo máximo para una función

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 }
about 4 years ago · Juan Pablo Isaza
1 answers
Answer question

0

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

about 4 years ago · Juan Pablo Isaza Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!