-2

I am using Angular 10 and have the following setInterval code working in my local:

ngOnInit() {
         this.myfunc();
         setInterval(this.myfunc.bind(this), 120000);
}

However, the same code is not working on the server. In other words, myfunc() is not triggering after 2 mins when running on the server.

Debugging Details:

In my local, this.myfunc() is called when the component is loaded for the first time. It is called again after 2 mins as per the setInterval()

However, when running on the server, this.myfunc() is called when the component is loaded for the first time. But it is not called again after 2 mins as per the setInterval()

meallhour
  • 13,921
  • 21
  • 60
  • 117

2 Answers2

1

Problem

setInterval sometimes drifts, as seen in this post.

Solution

Taken from this solution, you would first make a non-drifting class:

function AdjustingInterval(workFunc, interval) {
         let that = this;
         let expected, timeout;
         this.interval = interval;

         this.start = function() {
                  expected = Date.now() + this.interval;
                  timeout = setTimeout(step, this.interval);
         }

         this.stop = function() {
                  clearTimeout(timeout);
         }

         function step() {
                  let drift = Date.now() - expected;
                  workFunc();
                  expected += that.interval;
                  timeout = setTimeout(step, Math.max(0, that.interval - drift));
         }
}

and then, you would just use this instead for your code:

ngOnInit() {
         let ticker = new AdjustingInterval(this.myfunc.bind(this), 120000);
         this.myfunc();
         ticker.start();
}
Coder100
  • 161
  • 1
  • 12
0

I was able to resolve the issue by changing setInterval() to callback as follows:

setInterval(() => {
    this.myfunc(); }, 120000);

}

Updated ngOnInit() looks as below:

ngOnInit() {
         this.myfunc();
         setInterval(() => {
         this.myfunc(); }, 120000);
  }
}
meallhour
  • 13,921
  • 21
  • 60
  • 117