DEV Community

loading...
Cover image for JavaScript Interview Question #39: How does setTimeout work inside the loop?

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

coderslang profile image Coderslang: Become a Software Engineer Originally published at learn.coderslang.com ・1 min read

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

Discussion (3)

Collapse
elijahe35939317 profile image
ElijahE

What's the implication on performance?

Collapse
coderslang profile image
Coderslang: Become a Software Engineer Author

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 Author

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

Forem Open with the Forem app