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

204
Visualizações
Correctly delaying setTimeout

In the following function

function test1(n, delay) {
  for (let i = 0; i < n; i++) {
    setTimeout(() => {
      console.log(i)      
    }, delay)    
  }  
}

test1(3, 1000)

After 1 second, I immediately console.log 1, 2, and 3 simultaneously.

If I multiply delay by i,

function test1(n, delay) {
  for (let i = 0; i < n; i++) {
    setTimeout(() => {
      console.log(i)      
    }, i * delay)    
  }  
}

test1(3, 1000)

I console.log every i in my loop after 1 second. Why does this work?

Also, why does the code below

function test2(n, delay) {
  let promise = new Promise(resolve => setTimeout(() => {
    resolve()    
  }, delay))
  for (let i = 0; i < n; i++) {
    promise.then(console.log(i))  
  }  
}

test2(3, 1000)

immediately console.log 1, 2, and 3 simultaneously instead of waiting every second to console.log the next i value? Is there a way to console.log the next i value using promise chaining after waiting every second without using async and await?

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

0

The reason why we need to multiply i with delay is by doing that you set a timeout with timeout 1s/2s/3s. In the example, you make the console.log() execute it after 1 seconds, 2 seconds and 3 seconds.....

If you doesn't multiply the i with delay, then all timeout you assign using for loop will executed after 1 (delay) second at the same time (you could almost ignore the execution time of for loop.

Another solution to loop every second is to use setInterval:

let i = 0;
let interval;
function test2(n,delay){
 //Change millisecond to second
   delay*=1000
   interval = setInterval(function(){
       console.log(i);
       i++;
       if(i>n)
       window.clearInterval(interval)
    },delay)
   }
test2(10,1)

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