why the output of this snippet is 3,3,3 instead of 0,1,2 ?

Submitted 4 years, 4 months ago
Ticket #307
Views 344
Language/Framework Javascript
Priority Low
Status Closed

let i;
for (i = 0; i < 3; i++) {
  const log = () => {
    console.log(i);  }
  setTimeout(log, 100);
}
Submitted on Nov 26, 20
add a comment

1 Answer

Verified

The output is 3,3,3 because the loop ends before the setTimeout function is called.

Also, don't declare a function expression inside a loop. It's a waste of time

So, if you want to print 0, 1, 2, ..., 14 and add some delay between printing, this should work:

const log = i => console.log(i)

for(let i = 0;i < 15; i++){
    setTimeout(log, 1000 * (i + 1), i);
}

Submitted 4 years, 4 months ago

@mateigliga, Thanks for your answer.

- Vengat 4 years, 4 months ago


Latest Blogs