Chrome for Developers’ Post

View organization page for Chrome for Developers, graphic

2,836 followers

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); }

Yash Raj Bharti

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)

3d

Assumption - 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.

Like
Reply

To view or add a comment, sign in

Explore topics