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

191
Visualizações
How to break a nodejs for loop if the execution takes more than 20 seconds?

Suppose I have a forloop that does some execution. I would like to break the for loop if it takes more than 20 seconds to execute.

async function mainFunc(){

    for (let step = 0; step < 5; step++) {
        // Runs some complex operation that is computationally intensive
        //someFunc() is a async method. SomeAnotherFunc() is a synchronous one.
        await someFunc();
        someAnotherFunc();//this function contains built in function 
        // execSync() that runs command line functions 
        await someFunc(); 
 
    }
}

Can anyone provide me a simple solution where tracking the time and breaking the loop happens on a separate thread so that I don't burden my existing for loop execution?

This answer partially works for me. The solution given by @Molda will only help me in the case of Async methods. If you see the code snippet that I provided, there is a synchronous method called someAnotherFunc() which has a nodejs process function "execSync" that runs command line functions. Now it is actually a pain point for me to track the time of this function as I dont have access to the method as it is a built in function. I would appreciate on your suggestions on how to proceed further.

about 4 years ago · Juan Pablo Isaza
2 Respostas
Responde à pergunta

0

That should be fairly simple

var stop = false;
setTimeout(()=>{ stop = true; }, 20 * 1000);

for (let step = 0; step < 5; step++) {
    if (stop) break;
}

Note:

The for loop without async/await is synchronous which means even calling multiple requests/db calls/ etc. will only take less then a second for the for loop to finish. So i can't imagine what you would do in it that would take 20 seconds

about 4 years ago · Juan Pablo Isaza Relatório

0

Have you tried to add a timer inside the for loop and when it finish the 20 seconds to break?

How to do a timer in Angular 5
https://www.w3schools.com/js/js_break.asp

Something like this:

var stopTimer = false;
setTimeout(() => {
    stopTimer = true;
}, 20 * 1000);

for (let step = 0; step < 5; step++) {
    if (stopTimer) break;
}
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