连续调用moment.utc()不是顺序的

时间:2018-01-15 08:19:29

标签: javascript typescript knockout.js momentjs

使用Knockout,我们在typescript中运行以下代码:

    class timeHelpers {    

    private static createTimeBasedObservable(updatePeriodInMillis: number) {
        const nowTime: KnockoutObservable<moment.Moment> = ko.observable<moment.Moment>();
        let interval: number;

        const computed = ko.pureComputed(() => nowTime());

        computed.subscribe(() => {
            nowTime(moment.utc());
            interval = setInterval(() => nowTime(moment.utc()), updatePeriodInMillis);


        }, this, "awake");

        computed.subscribe(() => {
            clearInterval(interval);
            interval = undefined;
        }, this, "asleep");

        return computed;
    }

    static readonly utcNowWithMinutePrecision = timeHelpers.createTimeBasedObservable(60 * 1000);
    static readonly utcNowWithSecondPrecision = timeHelpers.createTimeBasedObservable(1000);

export = timeHelpers;
}

问题是连续调用

   ...
   const now = timeHelpers.utcNowWithSecondPrecision();
   now.add(moment.duration(this.serverTimeDifference())); 
   // this.serverTimeDifference() is some numerical value
   ...

生成并非总是顺序的值

查看此附加的控制台打印输出:

enter image description here

1 个答案:

答案 0 :(得分:0)

&#39;添加&#39;方法通过向其添加时间来改变原始时刻。 https://github.com/moment/momentjs.com/blob/master/docs/moment/03-manipulating/01-add.md

通过致电&#39;添加&#39;解决了这个问题。在克隆值:

  now.clone().add(moment.duration(this.serverTimeDifference()));