Javascript 循环通过数组对象的角度,每个项都有延迟

Javascript 循环通过数组对象的角度,每个项都有延迟,javascript,angular,angular5,angular6,Javascript,Angular,Angular5,Angular6,我在UI上工作,云在屏幕上水平移动 我有一个项目数组要显示在云上,数组中的每个项目都是一个云。该组件具有css显示绝对位置,因此我当前的方法是在每个组件之上创建一个组件堆栈。我的目标不是一次加载一个数组的项目,而是以4000ms的延迟加载每个项目。我知道在clouds.component.ts或html模板*ngFor中可能需要setTimeout()或setInterval() 我尝试了*ngFor=“let setTimeout(()=>item,4000)of items”,但似乎不正确

我在UI上工作,云在屏幕上水平移动

我有一个项目数组要显示在云上,数组中的每个项目都是一个云。该组件具有css显示绝对位置,因此我当前的方法是在每个组件之上创建一个组件堆栈。我的目标不是一次加载一个数组的项目,而是以4000ms的延迟加载每个项目。我知道在clouds.component.ts或html模板*ngFor中可能需要setTimeout()或setInterval()

我尝试了
*ngFor=“let setTimeout(()=>item,4000)of items”
,但似乎不正确

下面是我的组件结构

cloud.component.ts

export class CloudComponent {
 @Input('cloud') public element: {
  ....
  // not important
 }
}
export class CloudsComponent {    
 public clouds: Cloud[] = [item,item,item,item,item]
 // service call
}
clouds.component.html

<app-cloud *ngFor="let item of items" [cloud]="item"></app-cloud>

您必须以4000ms的超时时间将当前数组馈送到虚拟数组中

this.dummyItems=[]  
for(let i = 0; i < this.items.length; i++){
     let item = this.items[i];
     setTimeout(() => {
         this.dummyItems.push(item);
     }, 4000*(i+1));
 }
this.dummyItems=[]
for(设i=0;i{
this.dummyItems.push(项目);
},4000*(i+1));
}
在模板中

<app-cloud *ngFor="let item of dummyItems" [cloud]="item"></app-cloud>

您可以在组件中设置所有内容,然后使用
setInterval()
加载它们,然后在结束时杀死并销毁
setInterval()

dummyItems=[];
index = 1;
public clouds: Cloud[] = [item,item,item,item,item]

ngOnInit() {
  if( this.coulds[0]) { 
      this.dummyItems.push(this.clouds[0]);
  }
  this.timer = setInterval(() => {
      if (this.index < this.coulds.length) {
         this.dummyItems.push(this.clouds[index]);
         this.index++;
      } else { 
         clearInterval(this.timer); // this is optional but good practice
      }
   }, 4000)
}
dummyItems=[];
指数=1;
公有云:云[]=[项目,项目,项目,项目,项目]
恩戈尼尼特(){
如果(this.coulds[0]){
this.dummyItems.push(this.clouds[0]);
}
this.timer=setInterval(()=>{
if(this.index
您需要将for循环放入构造函数还是ngOnInit()?
ngOnInit()
就可以了,我认为这行不通。我想它会等待4秒钟,然后一次加载所有对象,因为for循环仍然在循环,即使在它调用timeout之后。当我尝试将for循环放入ngOnInit()@rhavelka中时,dummyItems数组是空的。不,不会,我在控制台中检查过
let
是在解决方案工作时按顺序执行异步的东西,但是第一个云也延迟了4000毫秒。您只需要在间隔之前推送第一个云,并在1开始索引。