Chrome for Developers’ Post

View organization page for Chrome for Developers, graphic

3,016 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)

1w

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

I agree!@ @

  • No alternative text description for this image
Like
Reply

Very helpful!

Like
Reply
Rajneesh Kumar

Seeking Internships in Frontend Web || Building network || HTML CSS JS Tailwind Bootstrap || C (level 4 hackerrank) || Figma PicsArt Kinemaster

5d

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

Like
Reply
See more comments

To view or add a comment, sign in

Explore topics