A loop in JavaScript/TypeScript that runs precisely once every minute

Here is a snippet of my code:

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

Although I prioritize having the updateData call occur every minute for data analysis purposes rather than ensuring it runs before other functions, I am experiencing fluctuation in the timing. The interval ranges from 1m 100ms to 1m 300ms. How can I guarantee consistency in the minute intervals even if other functions are executed in between?

Answer №1

setInterval and setTimeout may not provide the most precise timing for scheduling tasks, as they run on the main thread alongside other processes. For better accuracy, consider running your timers within a WebWorker, which operates in a separate thread.

Answer №2

If you want to repeatedly execute a function at specified time intervals in JavaScript, you can use the

setInterval(function() {}, timeInMilliseconds)
function. Learn more about it here.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Sending JSON object data to an API endpoint using the POST method in an Angular application

Attempted to post data to an API, but received a 400 bad request error. After testing with Postman, it seems that the issue may lie within my service or TypeScript code. As a newcomer to Angular, I am seeking assistance as I have searched extensively witho ...

Javascript is not fetching the value

Here is the code snippet I am working with: var categoryDetailId = $("#createEventForm-categoryDetail-idCategory").val(); and this link from my rendered page: After clicking the button, it returns NaN Update: I tried setting it manually, but it still ...

Configuration of an MVC-based web application

As a newcomer to web application development, I am currently working on building a web application using the Model-View-Controller pattern. My setup includes a MySQL database for the Model, JSP pages for the Views, and a DAO for the Controller. I am looki ...

Something is wrong with the conditional compilation in the JavaScript code

I encountered a "Conditional compilation is turned off" error in my JavaScript code. How can I resolve this issue? var <a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="176264726559767a722a6765727a763976397679747f786557626739786 ...

The Impact of Ajax on Online Search Algorithms

There's a website that dynamically loads content at . An example page from the site can be found at: . The entire content on this page is generated using a cURL parser script. <?php $___notjson=1; ini_set('display_errors', 1); header (&a ...

Is it possible in Cypress to invoke the .click() function on an Element without triggering any errors?

I am currently in the process of developing Cypress E2E tests for my Angular application. One specific page in the app features a table with a link in the third column that is identified by the class name 'link ng-star-inserted'. My goal is to h ...

Determining html column values using a related column and user input

Is there a way to populate an HTML table column (using Javascript or jQuery) based on the values in another column and an input field? For instance, if I input the number 115 into the field, then the advance column should display a value of 1 for each ath ...

Construct a string by combining the elements of a multi-dimensional array of children, organized into grouped

My task involves manipulating a complex, deeply nested array of nodes to create a specific query string structure. The desired format for the query string is as follows: (FULL_NAME="x" AND NOT(AGE="30" OR AGE="40" AND (ADDRESS ...

Generating an MD5 hash for a UTF16LE string in Javascript (with no BOM and excluding 0-byte at the end) - Illustrated with a C#

I've been trying to figure out how to get an MD5 Hash of a UTF16-LE encoded string in JavaScript for the past few days. I have a method in C# as an example, but I'm not sure how to replicate it in JavaScript. Example: public string GetMD5Hash ( ...

How about "Incorporate Google Auth into your Vue.js project with modular

I'm on the search for a project that showcases using Vue.js and the Google client library to authenticate with JavaScript, but without the need for transpilers, bundlers, or Node/npm. Does anyone know of such an example out there? I simply want to cre ...

Importing WebAssembly dynamically can sometimes lead to complications with the order of execution

I am attempting to load a WASM library from another node js application, both utilizing webpack. Within the WASM library, I have the following code snippet exporting the functionality. export default import("./pkg") .then(s => { le ...

Choose the list item below

I'm working on a website that includes a select list with images. Here's what I have so far: When I choose an image from the list, it should display below. <?php // Establish database connection $con=mysqli_connect("******","***","*** ...

Change the variable value within the service simultaneously from various components

There is a service called DisplaysService that contains a variable called moneys. Whenever I make a purchase using the buy button on the buy component, I update the value of this variable in the service from the component. However, the updated value does n ...

Looking for Efficiency in Basic JavaScript Arithmetic Operations

I'm having trouble figuring out how to display a total price after a selection is made. My goal is to take the selected value, multiply it by 100, and then use the updateTotal function to show the total. // Gather Data & Prices for Updating Dynamic P ...

How can the backgroundImage css in react admin <Login /> be replaced using Material-UI?

I have been refering to the following resources: Learn about customizing login page background in React-Admin: Explore themes customization in Material-UI: https://material-ui.com/customization/components/ Instead of using a preset background, I want to ...

Transferring selected radio button values to Javascript

This is an example of HTML code snippet: <tr> <td class="g"> Gender </td> <td class="g_input"> <input type="radio" name="gender" id="settings_gender" value="Male" checked />&nbsp;&nbsp;Male ...

Dynamically loading an AngularJS controller

I am faced with the challenge of integrating an Angular app with dynamically loaded controllers into an existing webpage. Below is a code snippet where I have attempted to achieve this based on my understanding of the API and some research: // Create mod ...

"Mastering the Geocoder Class: Unleashing the Power of AJAX for Latitude and Longitude Retrie

This JSON array includes a collection of addresses [ { "id": 0, "title": "Coop.Sociale Prassi e Ricerca Onlus", "latitude": 0, "longitude": 0, "address": "Viale Eleonora D'Arborea 12, Roma, IT" }, { "id": 0, "title": "San Lorenzo", "lati ...

Guide on sending a PUT request using express.js

Currently delving into node.js and have a query regarding PUT requests I'm able to create an object and see it in the URL. However, I'm unsure of how to write a request to edit it - such as changing the price of a vehicle. Any guidance on writin ...

Merge two arrays of objects in Ramda.js based on their shared ID property

I'm working with two arrays of objects: todos: [ { id: 1, name: 'customerReport', label: 'Report sent to customer' }, { id: 2, name: 'handover', label: 'Handover (in C ...