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

265
Visualizações
How to print number after a delay in JS

It's beginner's question. I'm trying to understand setTimeout. I want to print each number after a delay of 2 seconds. However, I can only delay the whole function, not the numbers. Can anyone tell me how to do it?

function print() {
  for (let i = 10; i >= 0; i--) {
    console.log(i);
  }
}

setTimeout(print, 2000);

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

0

You need to use the setTimeout inside the print method (inside the for), and give a different delay for each iteration.

function print() {
  for (let i = 10; i >= 1; i--) {
    setTimeout(() => {
      console.log(i);
    }, 2000 * (10 - i));
  }
}

print();

about 4 years ago · Juan Pablo Isaza Relatório

0

Another approach is using setInterval. It is more natural for this task then setTImeout.

let i = 10;
const interval = setInterval(() => {
  console.log(i);
  i--;
  if(i === 0){
    clearInterval(interval);
  }
}, 2000);

about 4 years ago · Juan Pablo Isaza Relatório

0

setTimeout here will delay all the function and if I get what you want to do is to print each number in 2s delay. ill recommend using Promises and async function. here is a solution with only setTimeout

function print(i){
  console.log(i)
  if(i>0){
    setTimeout(()=>{print(i-1)},2000)
  }
}
print(10)
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