Javascript setInterval 在本地工作但在服务器上

Javascript setInterval working in local but on the server

我正在使用 Angular 10 并在我的本地运行以下 setInterval 代码:

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

但是,相同的代码在服务器上不起作用。 换句话说,当服务器上 运行 时 myfunc() 不会在 2 mins 之后触发。

Debugging Details:

在我本地,第一次加载组件时调用this.myfunc()。根据 setInterval()

2 mins 之后再次调用

但是,当运行在服务器上时,this.myfunc()会在第一次加载组件时被调用。但它是 not2 mins 之后根据 setInterval()

再次调用

问题

setInterval 有时会漂移,如 .

所示

解决方案

取自,你首先要做一个非漂移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));
         }
}

然后,您只需将其用于您的代码:

ngOnInit() {
         let ticker = new AdjustingInterval(this.myfunc.bind(this), 120000);
         this.myfunc();
         ticker.start();
}

我能够通过将 setInterval() 更改为回调来解决问题,如下所示:

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

}

更新后的 ngOnInit() 如下所示:

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