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

240
Visualizações
Using a let in a for loop with setTimeout function

If the arguments to functions are passed by value in javascript how come the console.log() below seems to get its input by reference? Shouldn't each time it is invoked inside setTimeout just the value of i be passed and not its reference?

let i;

for (i = 1; i <= 5; i++) {
  setTimeout(function timer() {
    console.log(i);
  }, i * 1000);
}

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

0

Shouldn't each time it is invoked inside setTimeout just the value of i be passed and not its reference?

Yes, and this is exactly what is happening. It is passing the value of i by value to console.log(i). But, you're passing that value AFTER the entire for loop has completed when i has its terminal value because this is the order that things run:

  1. You declare let i.
  2. You start your for loop.
  3. The for loop runs to completion, each iteration starting an additional timer. The timer is non-blocking and asynchronous so it just starts the timer and execution of the loop continues.
  4. Then, sometime later (after the for loop is completely done) with the value of i sitting on its terminal value, then the timers start firing which causes them to call their callback and then output console.log(i).

Note, that if you made the let i be part of the for loop declaration, you would get completely different results:

for (let i = 1; i <= 5; i++) {
  // Because let i was inside the for loop declaration,
  // there is a separate copy of i for each iteration of the for loop here
  setTimeout(function timer() {
    console.log(i);
  }, i * 1000);
}

Because here there is special treatment for the let i in the for loop. Each iteration of the loop gets it own separate copy of i and thus it still has the value it had when the loop iteration was run at the later time when the timer fires.

This is completely different than your original version where there is only one i for the entire loop and its value is incremented on each iteration and thus the value i had when each iteration of the loop ran is no longer available when the timer fires.

about 4 years ago · Juan Pablo Isaza Relatório

0

for (let i=1; i<=5; i++) {
    setTimeout( function timer(){
        console.log( i );
    }, i*1000 );
}

This has to do with a very important concept called scope. A scope is the piece of code where your variable exists.

In your example you define the variable before the for loop. So this happens internally:

  • You create i
  • i is set to 1
  • i is referred to in your setTimeout() (5 times)
  • i is incremented by 1 ( 5 times )
  • i is logged 5 times, all as 6, because the values all refer to the same i

In my example i is scoped in the for loop. This means every iteration of the loop a new reference to i is generated. So these references refer to different variables from the computers point of view ( even tough your code names them all i ).

about 4 years ago · Juan Pablo Isaza Relatório

0

for (let i = 1; i <= 5; i++) {
  setTimeout(function timer() {
    console.log(i);
  }, i * 1000);
}

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