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

92
Visualizações
How to run multiple timers one after another with pause in javacript?

I need to run multiple timer one after another with pause. Input for timer comes from the array which contains set of times. I did something with reduce method. But could not break early the reduce method.

const times = [5, 4, 5];
function countDown(secs) {
        console.log(secs);
        if (secs === 1) {
            clearTimeout(timer);
            return timer;
        }
        secs--;
        var timer = setTimeout(() => countDown(secs), 1000);
}

times.reduce((totalDelay, time) => {
    setTimeout(() => {
        countDown(delay);
    }, 1000 * totalDelay);
    const delay = parseInt(time);
    totalDelay += delay;
    return totalDelay;
}, 0);

I tried with a boolean to pause and play. The timer is paused by that boolean variable but when I resume two timer is running because of the reduce.

Is there any other way to do this with loop or something?

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

0

You code looks way too complicated. All you have to do is setting the timeout inside a function (without arguments) and use that function as a callback to setTimeout.

const times = [5, 4, 5];
function countDown() {
    const secs = times.shift();
    if (typeof secs === 'number') {
        setTimeout(countDown, secs * 1000);
        console.log(`Next timer in ${secs} seconds`);
    } else {
        console.log('Done');
    }
}
countDown();

Here I'm removing an element from the start of the times array on each iteration. You could also leave the array unchanged and use an index to keep track of the progress.

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