Calling all web development debugging detectives! 🕵️ Put your skills to the test and help us uncover what the error is in this code. for (var i = 0; i < 5; i++) { setTimeout(() => console.log(i), 1000); }
Very helpful!
Use let to print 0-4, SetTimeout runs after 1s, and loops complete in that time. The value will become 5 and then it will be printed as 5
UXE (front end) Lead • Alumni of IIT BHU • Google Summer of Code Senior Mentor at Liquid Galaxy • Purveyor of impeccable UX at CybTEKK • Former Technical Advisor and Mentor of Frontend Team at Kashiyatra (IIT-BHU)
1wAssumption - I'm assuming what you're trying to achieve here is print the numbers from the 'for' loop in ascending order. Error in the code - The setTimeout inside the for loop will pop off the call stack after one second, but till then if it will reference the value of i, i will be 5, so we get 5 printed out 5 times. The solution - simply put the setTimeout outside setTimeout(()=> { for (var i= 0; i < 5; i++) console.log(i), 1000} ); And now, each time 'i' prints in the increasing order we assume as the output at the beginning.