-1

I am working on Angular 11 project. I want to loop the code after 'X' duration mentioned in JSON.data. Here is my following code snippet.

data.json

pageOrder: {
   pageDetails:[
   {
     "duration": 5
   },
   {
     "duration": 7
   }]
}

app.component.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;
    }
  }

Unfortunately, the code is looping only once, why???

JustCode
  • 661
  • 1
  • 8
  • 19

2 Answers2

2

setTimeout calls the function in a different scope. this doesn't point to the object. You need to bind the object

setTimeout(this.reloadFunction.bind(this), pageOrder[this.id].duration * 1000);
Thomas Sablik
  • 16,127
  • 7
  • 34
  • 62
0

Try following :-

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;
    }
  }
Aakash Garg
  • 10,649
  • 2
  • 7
  • 25