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

178
Visualizações
Timer console logs in sync JS

Wanted to print console.log in sync - * every second print console in sync one by one

Output should be

start a 3 second timer
3 second remaining 
2 second remaining
1 second remaining
after 3 second timer, start a 5 second timer
5 second remaining
4 second remaining
3 second remaining
2 second remaining
1 second remaining
both timers done!
Timer done!


 function main() {
      console.log('start a 3 second timer');
      printTimer(3, () => {
        console.log('after 3 second timer, start a 5 second timer');    
        printTimer(5, () => {
            console.log("both timers done!");
        });
      });
    }
    
    main();
    
    function printTimer(n, callback) {
         for (let i = 0; i < n; i++) {
            setTimeout(()=> console.log(`${n - i} seconds remaining`));
            }
      }
      setTimeout(() => console.log('timer done!'))
      callback()
    }

I am new to JS and wanted to know how can we get such console.logs Thank you in advance

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

0

Solution:

function main() {
    console.log('start a 3 second timer');
    printTimer(3, () => {
      console.log('after 3 second timer, start a 5 second timer');    
      printTimer(5, () => {
          console.log("both timers done!");
          console.log("Timer done!")
      });
    });
  }
  
  main();


async function printTimer(n, callback) {

    const waitForMilliseconds = ms => new Promise(resolve => setTimeout(resolve, ms))

    for (let i = 0; i < n; i++) {
        console.log(`${n - i} seconds remaining`)
        await waitForMilliseconds(1000)
    }

    callback()
}

about 4 years ago · Juan Pablo Isaza Relatório

0

Instead of nesting your functions and iterating over setTimeouts create a function that returns a promise, and inside that promise use a setTimeout to log the numbers to the console. If you use async/await you can then just wait for each promise to resolve.

function timer(n) {

  return new Promise((res, rej) => {

    // `loop` accepts an argument `i` which is the
    // initial value of n, but which gets reduced on
    // each iteration
    function loop(i) {

      // If `i` reaches zero pass back the resolve value
      if (i === 0) {
        res('Done');

      // Otherwise log the current value of `i`
      // and call the loop function again reducing
      // the value of `i`
      } else {
        console.log(`${i} seconds remaining.`);
        setTimeout(loop, 1000, --i);
      }
    }

    // Pass in the number, and start the loop
    loop(n);

  });

}

// Now just `await` the response from the promises
(async () => {
  console.log('Start a 3 second timer');
  console.log(await timer(3));
  console.log('After 3 second timer, start a 5 second timer');    
  console.log(await timer(5));
  console.log('Both timers done.');    
})();

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