Skip to content Skip to sidebar Skip to footer

For Loop, Let, And Settimeout

for (let i=1; i<=5; i++) { setTimeout( function timer(){ console.log( i ); }, i*1000 ); } Biggest thing I'm confused about here - Why does this print 1,2,3,4,5

Solution 1:

It is actually quite simple. The for loop schedules the timer function for all five values. Then the timer function starts printing the numbers. Now the reason for them being printed 1 second apart is i*1000 in setTimeout. As a result, 1 will be printed 1 second after it has been scheduled, 2 will be printed 2 seconds after it has been scheduled, and approximately 1 second after 1 has been scheduled, and so on...

See the snippet below to understand how it works. Keep in mind that setTimeout does not block the execution of the for loop.

for (let i=1; i<=5; i++) {
    setTimeout( functiontimer(){
        console.log( i );
    }, i*1000 );
    
    console.log("Print " + i + " after " + i +" seconds.");
}

console.log("for loop completed.");

Solution 2:

setTimeout() will place your timer() into the queue. for loop execute very quickly nearly immediately, each loop timer() will be placed into the queue with delays: 1,2,3,4,5 seconds respectively.

console.log(i) will print 1-5 because of the immediate execution of for loop.

Solution 3:

I guess what the other answers have not touched upon is the event loop.

The event loop is a distinct execution thread than the main JS thread. Your for loop would execute in the main JS thread, pushing each timeout on the event loop which would be executed in the event loop as scheduled. The time scale of events would look something like this.

enter image description here

Solution 4:

I hope this is what you are looking for System.Threading.Thread.Sleep(1000*i);

Post a Comment for "For Loop, Let, And Settimeout"