【问题标题】:Javascript setInterval working in local but on the serverJavascript setInterval 在本地工作但在服务器上
【发布时间】:2020-12-01 16:48:33
【问题描述】:

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

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

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

调试细节:

在我的本地,第一次加载组件时会调用this.myfunc()。它在2 mins 之后根据setInterval() 再次调用

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

【问题讨论】:

  • setInterval 有时会漂移。你考虑过漂流吗?
  • 不,我没有。您能建议如何计算吗?
  • 您能否建议更新后的代码在我的情况下看起来如何?谢谢
  • 你想让我给你发一个回复帖吗?

标签: javascript node.js angular settimeout setinterval


【解决方案1】:

问题

setInterval 有时会漂移,如this post 所示。

解决方案

取自this solution,你先做一个非漂移类:

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();
}

【讨论】:

    【解决方案2】:

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

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

    }

    更新后的ngOnInit() 如下:

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2012-10-03
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-09-10
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多