0

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);
    }
}
2
  • your for loop starts at 20 and minus's one till it gets to 1, this console logs instantly. Then It waits this i * 2000 time to print again Commented Jan 5, 2021 at 15:10
  • 1
    Because of the timer, it's still scheduling 1 at 2 secs, 2 at 4 secs, and so on. Commented Jan 5, 2021 at 15:11

2 Answers 2

2

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).

Sign up to request clarification or add additional context in comments.

Comments

1

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.