Employ the setInterval function to run a task every 15 minutes for a total of

I have a task that requires me to use setInterval function 5 times every 15 minutes, totaling one hour of work. Each value retrieved needs to be displayed in an HTML table.

Below is the table:

enter image description here

For example, if it is 7:58 p.m., the script starts running

At 08:00, the first value is 5

enter image description here

At 08:15, the first value is 3

enter image description here

At 08:30, the first value is 2

enter image description here

At 08:45, the first value is 1

enter image description here

I currently do not have any issues, my problem is explained below

At 09:00, the first value is 6

Please refer to the image below

enter image description here

The value 6 is displayed in the first column instead of the last. :S

Why does the timer reset to zero? Shouldn't it add another 15 minutes normally?

The desired result is shown in this image

enter image description here

let atomRunTimers = setInterval(() => {
  let minutes = new Date().getMinutes();
if (minutes === 0) {
    let val1 = parseFloat(atomStockObject.p).toFixed(3);
    let price = parseFloat(atomStockObject.p).toFixed(3);

    atomStockPriceElement1.innerText = price;
    atomStockPriceElement1.style.color =
      !atomLastPrice || atomLastPrice === price
        ? 'black'
        : price > atomLastPrice
        ? '#AAFF00'
        : 'red';

    atomLastPrice = price;
    atomStockObject = null;

  }

if (minutes === 15) {
    let val2 = parseFloat(atomStockObject.p).toFixed(3);
    let price = parseFloat(atomStockObject.p).toFixed(3);

    atomStockPriceElement2.innerText = price;
    atomStockPriceElement2.style.color =
      !atomLastPrice || atomLastPrice === price
        ? 'black'
        : price > atomLastPrice
        ? '#AAFF00'
        : 'red';

    atomLastPrice = price;
    atomStockObject = null;


  }

if (minutes === 30) {
    let val3 = parseFloat(atomStockObject.p).toFixed(3);
    let price = parseFloat(atomStockObject.p).toFixed(3);

    atomStockPriceElement3.innerText = price;
    atomStockPriceElement3.style.color =
      !atomLastPrice || atomLastPrice === price
        ? 'black'
        : price > atomLastPrice
        ? '#AAFF00'
        : 'red';

    atomLastPrice = price;
    atomStockObject = null;


  }

if (minutes === 45) {
    let val4 = parseFloat(atomStockObject.p).toFixed(3);
    let price = parseFloat(atomStockObject.p).toFixed(3);

    atomStockPriceElement4.innerText = price;
    atomStockPriceElement4.style.color =
      !atomLastPrice || atomLastPrice === price
        ? 'black'
        : price > atomLastPrice
        ? '#AAFF00'
        : 'red';

    atomLastPrice = price;
    atomStockObject = null;

  }

if (minutes === 60) {
    let val5 = parseFloat(atomStockObject.p).toFixed(3);
    let price = parseFloat(atomStockObject.p).toFixed(3);

    atomStockPriceElement5.innerText = price;
    atomStockPriceElement5.style.color =
      !atomLastPrice || atomLastPrice === price
        ? 'black'
        : price > atomLastPrice
        ? '#AAFF00'
        : 'red';

    atomLastPrice = price;
    atomStockObject = null;


  }


}, 60000);

I appreciate any assistance provided as I am eager to resolve this issue and gain a better understanding.

Answer №1

Upon reviewing your code, there are several issues that need to be addressed:

  • Repetitive code in each if branch
  • Incorrect use of datetime without tracking the starting moment
  • Using toFixed(3) on a string returned by parseFloat, causing issues with number comparison

Addressing the Question:

"Why does the stopwatch reset to zero instead of adding 15 minutes?"

The issue lies in setting the minutes variable to the current minutes retrieved from getMinutes() on a new Date object:

let minutes = new Date().getMinutes();

For instance, if the time is currently 09:00, the minutes value will be 0, triggering the first condition:

if (minutes === 0) { /*...

To rectify this issue, consider saving the initial minutes value and subtracting it from subsequent values to determine elapsed time.

Alternative Approach:

Your code could be streamlined and improved. Here's a simplified version with comments:

//const tickDuration = 15*60*1000; //15m
const tickDuration = 3000; //3s
const maxtimes = 5; //5times

// Set timer to trigger the onTrigger function after tickDuration ms
let timer = setTimeout(onTrigger, tickDuration);

// When the timer triggers...
function onTrigger(){
  // Fetch current price data
  const currentPriceRaw = fetchCurrentPrice();
  // Update the displayed price
  const currentPrice = updatePrice(currentPriceRaw);
  // If the event hasn't occurred maxtimes yet, set another timer
  if(prices.length < maxtimes)
    timer = setTimeout(onTrigger, tickDuration);
}

The revised strategy utilizes setTimeout for scheduling function calls, ensuring efficient execution. Check out the demo for a clearer understanding!

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

Having difficulty creating the probot.github app due to an error: The removal of the programmatic API in npm version 8.0.0 causing failure

Currently, I am facing an issue while attempting to set up the probot.github app using the command npx create-probot-app my-first-app which can be found at: . My system is running on the latest node version v19.3.0 with npm version 9.2.0. However, upon exe ...

`There was an error in require.js stating that the property '$' of object #<Object> is not a function.`

Recently, I decided to give require.js a try for the first time, but unfortunately, I encountered an error that left me puzzled: Uncaught TypeError: Property '$' of object # is not a function. require.config({ shim: { "jquery" ...

Module not found (Error: Module not found for './models/campground')

Here is the code snippet I am working with: var express = require("express"), app = express(), bodyParser = require("body-parser"), mongoose = require("mongoose"), Campground = require("./models/campground"), Comment = require("./mode ...

Angular Directive - introducing a fresh approach to two-way binding and enable "pass-by-value" functionality

In a previous question, I inquired about the possibility of incorporating an attribute on a directive to allow for values to be passed in various formats, such as: <my-directive att> //Evaluates to true <my-directive att="true"> ...

JavaScript: Locate the HTML Attribute that Matches an ID

If you want to use just JavaScript, without relying on libraries like JQuery, how can you retrieve the data attribute associated with a specific Id? For example: <div id="id-test" data-qa="data-qa-test"> </div> Input: &quo ...

Verifying that the mapDispatchToProps functions have been triggered using ReactTestingLibrary

I am currently utilizing mapDispatchToProps to invoke a dispatch function that calls an API within the useEffect hook of my functional component. I am facing some challenges when attempting to write unit tests for this scenario using React Testing Library ...

The jQuery click function triggers immediately upon the loading of the page

Despite my best efforts to resolve this issue independently and conduct extensive research on Google, I am still unable to identify the root of the problem. It seems that the click function continues to activate upon page load. Kindly elucidate the under ...

Angular 5 offers the ability to incorporate dynamic checkbox input into your application

Here is my code snippet: <input [type]="'checkbox'" [(ngModel)]="inputValue"> <p>Value: {{ inputValue }}</p> I'm puzzled as to why the value in inputValue remains unchanged. Can anyone shed light on this? I am unable to ...

How to retrieve client's hostname using Node and Express

How can the client's hostname be retrieved in a Node / Express server? Is there a method similar to req.connection.remoteAddress that can be used to obtain the client's hostname? ...

Transmit data from Raspberry Pi to Apache Server with strong security measures

Utilizing a Raspberry Pi to collect temperature data and store it in a file Running on a virtual machine, the server uses Apache to host a website (comprised of HTML, PHP, and JavaScript) displaying a graph based on this data I am seeking a secure method ...

Can you explain the purpose of the yarn command --prefer-offline?

After installing an npm package like react for the first time using yarn add react I noticed that the .yarn-cache folder contains many files. I assume this is where yarn stores the local cache, so when I install react again in the future, it will be pulle ...

Ways to incorporate a custom JavaScript function that is activated by an external server system?

I'm currently exploring a JavaScript widget that needs to operate within specific constraints: The widget initiates a request to a third-party server using a callback URL The third-party server pings the callback URL after a set period, triggering a ...

Utilizing Selenium to inject javascript permanently or on every page refresh

In my selenium webdriver test using Python 3, I have implemented a semi-automated process. This means that some routines are automated while other tasks require user interaction with the browser, such as page refreshes or redirects. My challenge is to inj ...

ES6 promises: the art of connecting functions with parameters

Looking for a way to chain functions with delays? Here is an example of what I have tried: Promise.resolve() .then(setKeyframe('keyframe-0')) .then(delay(3000)) .then(setKeyframe('keyframe-1')) .then(delay(3000)) .then(setKeyframe(&apo ...

What is the best way to display a message on the 403 client side when an email sending fails?

I am attempting to display an alert message when the email is sent successfully or if it fails. If it fails, I receive a 403 status code from the backend. However, I am unsure how to handle this error on the client-side. In the case of success, I receive a ...

When $routeChangeStart is triggered, the location fails to locate the corresponding template

In my web application, I have an app variable associated with the module myApp. There are 3 pages: /login, /registration, and /. The behavior of $routeChangeStart is defined as follows: First, it checks if a global variable user is defined. If yes, it mo ...

Hide jquery scroll bar

I am currently working on a WordPress plugin with the Twenty Thirteen theme. My goal is to display a modal when a div is clicked, and at that time I want to hide the scrollbar on the body of the page. Despite trying the following code snippet, it doesn&ap ...

Choosing particular contenteditable divisions using jQuery

Consider the following HTML structure for a specific type of blog post editor: <div class="entry"> <div class="title" contenteditable="true"> <h2>Title goes here</h2> </div> <div class="content" contenteditable ...

Trouble Logging In: User Login Issue with SailsJS and PassportJS Plugin (sails-generate-auth)

I'm currently facing an issue with user authentication in my SailsJS app using PassportJS. I followed a tutorial on setting up authentication in SailsJS using sails-generate-auth, which can be found here. The POST request seems to be routed correctl ...

Utilize Vue.js to easily upload images alongside form input fields

I have recently started a small project with Vue Js. I am trying to incorporate an upload file option in my contact form. Due to the numerous input text fields, I am using serialize for the form. However, I am facing issues with the append function. How ca ...