Answer the question
In order to leave comments, you need to log in
How do timeout loops work?
I was interested in the task that I received at the interview
, there is the first cycle
let i = 0;
for (i = 0; i < 5; i++) {
setTimeout(() => console.log(i), 1000);
}
for (let i = 0; i < 5; i++) {
setTimeout(() => console.log(i), 1000);
}
Answer the question
In order to leave comments, you need to log in
The first thing to understand is that the timer works asynchronously, which means it will be executed after the loop.
Second - let has a block scope (the variable is visible in the block where it was declared, while the first operand for is considered the same block as the loop body)
Third - loops create a new scope for each iteration (each iteration will have its own let i , provided that this statement is inside the loop)
Well, in your examples, 1000 does not refer to the timeout, it's just a useless operation, and the timeout will get the default value - 0, I think this is not quite what you expect.
Another important point, a function expression (and an arrow function is also a function expression) inside the loop will create a function at each iteration of the loop. This is very bad both in terms of memory and performance (such functions will also be compiled and optimized separately). And if in the case of let inside the loop, the functions will at least differ in closure (each will close its i), then in the first case there will be 5 absolutely identical functions.
Here you can show yourself very well if, in addition to explaining the principles of work, remember that setTimeout can pass arguments to its callback:
const f = i => {
console.log(i);
};
for (let i = 0; i < 5; i++) {
setTimeout(f, 1000, i);
}
in the first case you have one global variable i.
the set 5 timers will work in a second and all will display its current value.
in the second case there are two variables i. loop parameter and global.
but there is also a lambda closure.
I rarely write in javascript. In other languages, the problem is solved in different ways.
for example the special final modifier. And somewhere, as in your case
, an implicit copy of a variable is created that is already used in a deferred event
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question