Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

221
Visualizações
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 Respostas
Responde à pergunta

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 Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda