82.8k views
3 votes
For (let i = 0; i < 5; i++) {

setTimeout(function() { (i); }, i * 1000 );
}
What will this code print?

User Alston
by
8.6k points

1 Answer

3 votes

Final answer:

The JavaScript snippet will schedule the printing of numbers 0 to 4, one second apart, assuming a console.log(i) is included within the setTimeout function.

Step-by-step explanation:

The code provided is a JavaScript snippet that creates a loop and schedules output using setTimeout. However, the function within the setTimeout call is missing a command to print the value of i.

Assuming the intent was to log the value to the console, if a console.log(i) call were included inside the function, the code would print the numbers 0 to 4 to the console, each one second apart.

Due to JavaScript's closure within loops, all scheduled functions will reference the same memory for i, but because let is block-scoped, each iteration actually captures the current value of i at the time the setTimeout was created.

User James Culshaw
by
8.5k points