Angular 2 wait / timeout before running a command

I have the following loop:

for (let i = 0; i < data.numChanges; i++) { 
                    console.log("Try numebr #" + i);
                    this.enemy.image = 'images/items/glasses/glasses.png;
                    //Wait 2 seconds, and show this image:
                    this.enemy.image = oldImage;
                    //Wait 1 second before processing to the next loop item
                }

What code do I need to place, where are the comments (see code above) so that the application "waits" before executing the given lines of code?

This is what I need to do:

  • Wait 2 seconds after changing the old image (first comment)
  • Wait 1 second at the end of the loop (second comment)
+4
source share
1 answer

I think this is what you are looking for:

for (let i = 0; i < data.numChanges; i++) { 
    console.log("Try numebr #" + i);
    this.enemy.image = 'images/items/glasses/glasses.png;
    //Wait 2 seconds, and show this image:
    setTimeout(() => this.enemy.image = oldImage, 2000);
    setTimeout(() => ...some code, 1000)
}

Basically you end your code in setTimeout(() => ..some code, 2000), 2000 is the timeout in ms, so 2000ms == 2s.

+10
source

All Articles