Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Angular 2 wait/timeout before executing 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 the comments located (see code above) in order to make the app "wait" before executing the given lines of code?

This is what I need to do:

  • Wait 2 Seconds after the old image has changed (first comment)
  • Wait 1 Second at the end of the loop (second comment)
like image 477
TheUnreal Avatar asked Jul 12 '16 16:07

TheUnreal


Video Answer


2 Answers

I think this is what you're looking for:

for (let i = 0; i < data.numChanges; i++) { 
  console.log("Try number #" + 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 wrap your code in setTimeout(() => ..some code, 2000). The 2000 is the time to wait in ms therefore 2000ms == 2s.

like image 65
Filip Lauc Avatar answered Sep 19 '22 12:09

Filip Lauc


I'm not sure of what you're trying to acheive, but I'll go with a state and a setInterval :

var nbiter=data.numChanges;
var state=0;
var anenemy=this.enemy;
var interF = setInterval(function(){
    switch(state){
    case 0:
        anenemy.image='images/items/glasses/glasses.png';
        state++;
        break;
    case 1:
        state++;
        break;
    case 2:
        anenemy.image=oldimage;
        if(--nbiter==0)
            clearInterval(interF);
        state=0;
        break;
    }
},1000);
like image 35
PiGo Avatar answered Sep 17 '22 12:09

PiGo