DEV Community

Cover image for JavaScript Interview Question #39: How does setTimeout work inside the loop?
Coderslang: Become a Software Engineer
Coderslang: Become a Software Engineer

Posted on • Originally published at learn.coderslang.com

JavaScript Interview Question #39: How does setTimeout work inside the loop?

js-test-39

What will be logged to the console?

.

.

.

.

.

.

.

.

.

.

.

.

.

.

.

.

.

Before we analyze the code snippet, let’s try to simplify it by removing the setTimeout.

If we just leave the plain console.log in the loop, then the output is all the values of i from 0 to 4 printed on each iteration of the loop.

However, when the setTimeout is added, the console.log will be executed after the loop has already been processed and the value of i is 5.

As i was declared with var, it has the global scope and the intermediary values aren’t stored in closure around the arrow function () => console.log(i).


ANSWER: the value 5 will be printed on the screen 5 times. Each time on the new line.

Learn Full-Stack JavaScript

Top comments (4)

Collapse
 
infiniteprism profile image
Infinite Prism

It should be noted that to get the intended outcome of printing 0 to 4, you can declare i with let instead of var.

This will give the variable i block scoping instead of function scoping and will prevent i from being hoisted to the global scope. The setTimeout function is an asynchronous function and since JavaScript is single-threaded, the setTimeout is passed to the browser's web api (which handles asynchronous functions) along with any bound variables. Declaring i with var does not bind it with setTimeout; instead it gets hoisted and the for-loop iterates all five loops before the setTimeout's callback is executed resulting in i equaling 5 by the time it is called thus printing 5 five times. By declaring i with let, i gets binded to the setTimeout so when it is passed, each callback function that gets passed into the task queue has its own i with the value that was passed in during the for-loop iterations thus printing 0 - 4.

Collapse
 
elijahe35939317 profile image
ElijahE

What's the implication on performance?

Collapse
 
coderslang profile image
Coderslang: Become a Software Engineer

The question here isn't as much about performance, it's about properly understanding the way asynchronous operations work in JS.

Collapse
 
coderslang profile image
Coderslang: Become a Software Engineer

JavaScript is async by design. There are no immediate problems with it if applied correctly.