Reputation: 21
I have a problem, I don't understand why my "console.log" from the "startAnimation" function
Shows me well: 20 19 18 ...
While in the "animationAnimation" function it returns me i = 1 i = 2 ....
animationAnimation(i, self) {
setTimeout(function() {
console.log("i =" + i);
}, 2000 * i);
return self;
}
startAnimation(self) {
for (let i = 20; i > 0; i--) {
console.log(i);
self.animationAnimation(i, self);
}
}
Upvotes: 0
Views: 45
Reputation: 36426
Let's go through step by step You are going through a for loop which outputs 20 19 18 ....1 to the console.
startAnimation(self) {
for (let i = 20; i > 0; i--) {
console.log(i);
self.animationAnimation(i,self);
In that for loop, first of all with i==20, you call animationAnimation.
animationAnimation(i, self) {
setTimeout(function () {
console.log("i =" + i);
}, 2000 * i);
return self;
}
That sets a timer which says 'after 40 seconds, output i =20 to the console'
Then you call it from the for loop with i==19 which says 'after 38 seconds, output i =19 to the console'
and so on right down to i==1 which says 'after 2 seconds output i =1 to the console.
So, although the for loop goes from 20 down to 1 and happens immediately, you have set 20 timers which do things at different times, and the i =1 will get to the console first.
Upvotes: 1
Reputation: 89159
You are using setTimeout
with the delay being 2000 times the index, so the smaller indexes will have less delay and thus be executed first.
If you want the maintain the reverse order of execution, you can calculate the delay using 2000 * (max - i)
, or in this case 2000 * (20 - i)
.
Upvotes: 2