Home > OS >  Set maximum time for a function
Set maximum time for a function

Time:03-16

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
}

CodePudding user response:

Using the setTimeout() method may be useful. https://developer.mozilla.org/en-US/docs/Web/API/setTimeout

CodePudding user response:

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

  • Related