JavaScript/TypeScript loop exactly every minute

Viewed 207

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?

2 Answers

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.

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

Related