2

My code look like this:

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

however it is not important for me that the data gets updated before any other function runs it, what is more important is that the updateData call happens exactly every minute, since i need to analyze the data based on a consistent interval. Now it fluctuates between 1m 100ms to 1m 300ms. Is there a way to make sure that's the case, even if other functions run inbetween?

  • 1
    have you tried `setInterval`? – apple apple Jul 01 '21 at 07:23
  • [setInterval](https://developer.mozilla.org/en-US/docs/Web/API/WindowOrWorkerGlobalScope/setInterval) – ciekals11 Jul 01 '21 at 07:24
  • Have you already taken a look at this question and if yes, what's different? https://stackoverflow.com/questions/196027/is-there-a-more-accurate-way-to-create-a-javascript-timer-than-settimeout – A_A Jul 01 '21 at 07:25

2 Answers2

2

setInterval and setTimeout are not the most precise way to schedule a task, because they're executed on the main thread, which shares CPU time with other processes. If you want more accuracy, then you're going to have to run your timers in a WebWorker, which executes code in a separate thread.

Andor Polgar
  • 483
  • 3
  • 13
-1

There is a javascript function called setInterval(function() {}, timeInMilliseconds) to do this: here.