All 28 lessons ▾
Inside JavaScript · Lesson 11 of 28
setTimeout in a Loop: The Classic Closure Interview Question
So, print one to five, one per second. Easy. But most people use var, and get six, five times! So let's see why, and three ways to fix it.
A new lesson goes up every day at 11 am. Subscribe on YouTube so you don't miss it.
Got a doubt? Ask in the comments under the video.Subscribe
- setTimeout never pauses: JavaScript moves on
- The callback runs later, and remembers its variables
- var: one shared i, so 6 five times
- let: a new i every round, so 1 to 5
- Only var? A function per round, each with its own copy
- Bonus: setTimeout's third argument
Part 1JavaScript waits for nobody
So today's episode is about one of the most famous JavaScript interview questions ever. It mixes setTimeout with closures, and it trips up a lot of people. But before we crack it, we need to understand one thing about setTimeout. Now you know the old saying, time and tide wait for none? Well, JavaScript doesn't wait for anyone either! So let's see what that means.
1function order() {2 var item = "pizza";3 setTimeout(function () {4 console.log(item + " delivered");5 }, 3000);6 console.log("order placed");7}8order();order placed pizza delivered
So look at this program. A function order, with a variable item, which is pizza. Then a setTimeout, holding a function that logs item delivered, after three thousand milliseconds. That's three seconds. And at the end, it logs order placed. Global is pushed, and phase one stores order. Line eight calls order. A brand new context is pushed, and its local memory gets item. Line two, item becomes pizza. Now line three, the setTimeout. Most people expect JavaScript to stop right here, wait three seconds, and only then move on. But no! setTimeout takes that function, attaches a three second timer to it, and keeps it aside. And JavaScript moves on, immediately. Line six runs, and it logs order placed. order is done, so it's popped. And the global code is over too, so Global goes, and the call stack is empty. Three seconds later, the timer is up. The function comes back to the call stack, and runs. Line four logs item plus delivered. And it prints pizza delivered! Then it's popped, finished.
So here's what setTimeout really does. You hand it two things, a function, and a time. setTimeout registers the function with a timer, and the timer does all the waiting. Not JavaScript. JavaScript just carries on with the next line. And when the time is up, the function is sent back to the call stack, and only then does it run. Now how exactly it gets back is a beautiful story called the event loop, and we'll see it in episode fifteen. So for now, remember this. JavaScript never waited, not even for a second.
And now here's the closure part. When the pizza function finally ran, order was long gone. Its box was deleted. So how did it still know that item was pizza? Because that function was a closure! It carried item along in its backpack, just like we saw in the last episode. Wherever the function goes, even into a timer, its backpack goes with it. So remember these two things. setTimeout doesn't pause JavaScript. And its function remembers the variables around it. Now we're ready for the big question.
Part 2The famous interview question
So here it is. The interviewer says, print one after one second, two after two seconds, three after three seconds, all the way up to five. Sounds simple. So let's write it the way most people do, and run it line by line.
1function count() {2 for (var i = 1; i <= 5; i++) {3 setTimeout(function () {4 console.log(i);5 }, i * 1000);6 }7 console.log("all timers set");8}9count();all timers set 6 6 6 6 6
So here's how most people write it. A function count, with a for loop from one to five, using var i. Inside the loop, a setTimeout that logs i, after i times one thousand milliseconds. So one second, two seconds, and so on. Phase one stores count. Line nine calls count, and its new context gets i, as undefined. Line two, the loop starts, and i is one. Line three sets the first timer, for one second. And JavaScript doesn't wait for it, remember? The loop goes round and round, setting a timer every time. Two seconds, three, four, five. Now i becomes six, and the loop stops. Line seven prints all timers set. count is done, so it's popped. Now the timers start firing. After one second, the first function logs i. Six! Then six. Six. Six. And six. So we asked for one to five, and we got five sixes!
So why six? Here are the five functions that setTimeout stored. One for each round of the loop. Now the key question. Which i does each function remember? Think back to the last episode. A closure keeps a reference to the variable, not a copy of its value. And with var, there's only one i, for the whole function count. Not one per round. Just one. So all five functions point to that same i. And the loop doesn't wait for any timer, so it finishes in a blink, and that one i becomes six. So when the timers fire, every function opens its backpack, looks at that same i, and finds six. Six, five times.
So remember this. With var, the whole loop has just one i. All five functions remember that same variable, not the value it had when each function was made. And by the time they run, the loop is long over, and i is six. So that's the entire mystery. Simple. Now let's fix it.
Part 3Fix one: let
So the first fix is so small, you won't believe it. We change just one word.
1function count() {2 for (let i = 1; i <= 5; i++) {3 setTimeout(function () {4 console.log(i);5 }, i * 1000);6 }7 console.log("all timers set");8}9count();all timers set 1 2 3 4 5
Now look at line two. var becomes let. Nothing else changes. So let's run it. The loop sets all its timers, and line seven prints all timers set, just like before. Now the timers fire. After a second, we get one. Then two. Then three. Four. And five! Exactly what the interviewer asked for. So one word, and the bug is gone. But why does let work? Let's see.
Because let is block scoped. Remember episode nine? Every round of a for loop is a new block. So with let, JavaScript creates a brand new i for every single round. Round one gets its own i, holding one. Round two gets its own i, holding two. And so on, all the way to five. So every function packs a different i in its backpack. Five functions, five separate variables. Now when the timers fire, each function opens its own backpack, and finds its own number. So that's why let just works.
So remember this. var gives the whole loop one shared i. let gives every round its own fresh i. One shared variable, versus five separate ones. And that single difference decides whether you print six, six, six, six, six, or one, two, three, four, five.
Part 4Fix two: only var
Now, here's where the interview gets interesting. The interviewer smiles, and says, great, but you're not allowed to use let. Do it with var. So what now?
1function later(n) {2 setTimeout(function () {3 console.log(n);4 }, n * 1000);5}6 7for (var i = 1; i <= 5; i++) {8 later(i);9}1 2 3 4 5
So here's the trick. We create a closure on purpose. We write a small function, later, which takes a number n, and sets the timer using n. And the loop, still with var, simply calls later with i. To keep it short, the loop sits right at the top level this time. Now watch closely. Phase one stores later, and i. Line seven, the loop starts, and i is one. Line eight calls later with i. A new context is created, and its own n gets the value one. A copy, taken right now. Line two sets the timer, and that function packs n in its backpack. Not i, but n! Then later is done, and popped. Next round, i is two, and line eight runs again. A brand new context, with a brand new n, which is two. And so on, for every round. In the end, i becomes six. But this time, nobody is looking at i! Each function has its own n. So when the timers fire, we get one, two, three, four, and five!
So remember this trick. Every time you call a function, you get a brand new execution context, with brand new variables. So by wrapping setTimeout in a function, and calling it each round, every timer gets its own copy of the number. Now that's a closure, used on purpose. And this is exactly the answer the interviewer was hoping for.
1for (var i = 1; i <= 5; i++) {2 setTimeout(function (n) {3 console.log(n);4 }, i * 1000, i);5}And now here's a bonus, a third way, which very few people know. setTimeout can take extra arguments, after the time. And when the timer fires, it passes them into your function. So here, we pass i as a third argument. setTimeout reads its value right away, in every round, and hands it to the function later, as n. No shared variable, no surprise. One, two, three, four, five. Mention this in an interview, and watch their eyebrows go up!
1for (var i = 0; i < 3; i++) {2 setTimeout(function () {3 console.log(i);4 }, 0);5}6console.log("done");This time, the delay is zero. Zero milliseconds! So what gets printed, and in what order?
Show the answer
First, done. Because even a zero millisecond timer never interrupts the code that's running. Its function has to wait until all of that is finished. And then? Three, three, three. One shared i, and the loop ended at three. Did you get it right? Now why even zero has to wait, that's the event loop, and you're going to love that episode.
Had you seen this question before, in an interview?
Answer in the comments under the video.
The video on YouTube, and the lesson as a swipe-through on Instagram.