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

x();

so I was Expecting That the output would be 5 5 5 5 5 as because of setTimeout the loop will complete its cycle and because of that closure will have that i=5 as the condition is i<=5 but the output is 6 6 6 6 6 and I just want to clear it up that how it broke the loop and went to 6?

b m gevariya
  • 300
  • 1
  • 4
  • 12
  • try `for(let i=1; i<=5; i++){` – Jaromanda X Aug 27 '23 at 10:09
  • `i` is equal to 6 by the time the timeouts run, because it increments after each loop iteration. When it reaches 6 the loop stops running, but that doesn't mean the variable is prevented from reaching it. – Robin Zigmond Aug 27 '23 at 11:13

0 Answers0