【问题标题】:JavaScript/TypeScript loop exactly every minuteJavaScript/TypeScript 每分钟循环一次
【发布时间】:2021-09-13 06:30:20
【问题描述】:

我的代码如下所示:

 async run(minutesToRun: number): Promise<void> {
    await authenticate();
    await this.stock.fillArray();
    await subscribeToInstrument(this, this.orderBookId);
    await subscribeToOrderbook(this, this.orderBookId);
    await this.updateLoop(minutesToRun);
}

sleep(ms) {
    return new Promise((resolve) => setTimeout(resolve, ms));
}

async updateLoop(minutesToRun: number) {
    const startTime = new Date();
    const timeDiff = compareTimestamps(startTime, this.currentTime);
    while (timeDiff < minutesToRun) {
        console.log(timeDiff);
        this.currentTime = new Date();
        this.timeStampArray.push(this.currentTime);
        console.log(this.timeStampArray);
        await this.stock.updateData();
        await this.sleep(60000);
    }
}

但是对我来说,在任何其他函数运行之前更新数据并不重要,更重要的是 updateData 调用每分钟发生一次,因为我需要根据一致的时间间隔分析数据。现在它在 1m 100ms 到 1m 300ms 之间波动。有没有办法确保这种情况,即使其他功能在两者之间运行?

【问题讨论】:

标签: javascript typescript loops settimeout


【解决方案1】:

setIntervalsetTimeout 不是调度任务的最精确方式,因为它们在主线程上执行,与其他进程共享 CPU 时间。如果您想要更高的准确性,那么您将不得不在 WebWorker 中运行您的计时器,它在单独的线程中执行代码。

【讨论】:

    【解决方案2】:

    有一个名为 setInterval(function() {}, timeInMilliseconds) 的 javascript 函数可以执行此操作:here

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2021-09-13
      • 2017-06-30
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2023-03-16
      • 1970-01-01
      • 2020-02-01
      相关资源
      最近更新 更多