我正在从事Angular 11项目。我想在JSON.data中提到的"X"持续时间之后循环代码。以下是我的代码片段。
data.json
pageOrder: {
pageDetails:[
{
"duration": 5
},
{
"duration": 7
}]
}
应用程序组件.ts
id: any = 0;
reloadFunction();
....
....
....
reloadFunction(): void {
// most of your code
console.log('wassup'); //**this should run after "duration", unfortunately its not working**
setTimeout(this.reloadFunction, pageOrder[this.id].duration * 1000);
this.id += 1;
if (this.id === pageOrder.length) {
console.log('wassup1', this.id);
this.id = 0;
}
}
不幸的是,代码只循环一次,为什么???
setTimeout
调用不同作用域中的函数。this
没有指向对象。您需要绑定对象
setTimeout(this.reloadFunction.bind(this), pageOrder[this.id].duration * 1000);
尝试以下操作:-
reloadFunction(): void {
console.log('wassup');
setTimeout(() => this.reloadFunction(), pageOrder[this.id].duration * 1000);
this.id += 1;
if (this.id === pageOrder.length) {
console.log('wassup1', this.id);
this.id = 0;
}
}