Javascript Angular 2 在执行命令之前等待/超时
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/38334671/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Angular 2 wait/timeout before executing a command
提问by TheUnreal
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)
- 旧图像更改后等待 2 秒(第一条评论)
- 在循环结束时等待 1 秒(第二条评论)
回答by Filip Lauc
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.
基本上,您将代码包装在setTimeout(() => ..some code, 2000)
. 该2000
是在毫秒等待因此2000MS == 2秒的时间。
回答by PiGo
I'm not sure of what you're trying to acheive, but I'll go with a state and a setInterval :
我不确定你想达到什么目的,但我会用一个 state 和一个 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);