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

210
Views
Set maximum time for a function

I need to set a maximum time for a function in Javascript so the function will automatically stop after a certain time if it hasn't been finished yet, Any solution how to do that?

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

You can try to execute your function on async mode, so you can controls it with promises:

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!