DEV Community

loading...

Discussion on: What’s your favorite JS interview question?

Collapse
jakebman profile image
jakebman

Feel free to run it and prove me wrong, but I believe that it prints 10 ten times, at 1 second intervals.

It's due to binding on the variable I, not the value of I when you create the lambda.

You need to introduce a local variable in the loop body to fix it.

Thread Thread
akashkava profile image
Akash Kava

You are wrong, if you use for(let i instead of for(var i it will print 0 to 9 correctly. jsfiddle.net/uh86qx1v/1/

Thread Thread
hiattzhao profile image
Hiatt

Can you explain why that happens? I'm new to ES6 and learned that let has block scope. When used in the for loop, in conjunction with setTimeOut set to 1000, you would think the console.log would run every 1000 ms for each console.log. But this doesn't happen. When I tried it, the sequence of console.logs appear all at once after 1000 ms. Why does that happen? Is it because setTimeOut, when called 10 times, gets pushed to the stack, then after 1000 ms the stack does its thing and all 10 calls are executed simultaneously?

If you take out the setTimeOut and just do console.log within the for (var i loop you get the correct result as well.

Thread Thread
jakebman profile image
jakebman

Yup, you're correct. The callbacks are registered very close to each other - they're all queued up to run at basically the same time.

Thread Thread
jakebman profile image
jakebman

Akash - this is the local variable I was trying to describe: jsfiddle.net/e7gyc5ts/1/ (I needed an IIFE to solve a problem that is better solved by let)

Thread Thread
ufocoder profile image
Thread Thread
bharath_bheemireddy profile image