Using JavaScript to calculate the difference between the current hour's value and the previous hour's value

Just started experimenting with JavaScript yesterday and was given a small task to create a script for a building controller. The task involves reading values from specific locations, performing energy calculations, and then after 1 hour, subtracting the initial values to get the delta energy difference. To keep the script running constantly, I am using a while loop with sleep function.

Below is the code I have developed so far:

function sum() {
   var E1 = (parseFloat(read("location1","value1")) *
   parseFloat(read("location11","value11"))) / Math.pow(10,6)
 
   executePropertyCommand("object1","Value","Write", E1) 
   
   var E2 = (parseFloat(read("location2","value2")) *
   parseFloat(read("location22","value22"))) / Math.pow(10,6)
 
   executePropertyCommand("object2","Value","Write", E2)
 
   var  IT_Sum = (E1 + E2) 
    return IT_Sum}

 setTimeout(sum1,3.599 * 1000000);{
 function sum1() {
   var E1 = (parseFloat(read("location1","value1")) *
   parseFloat(read("location1","value1"))) / Math.pow(10,6)
 
   var E2 = (parseFloat(read("location2","value2")) *
   parseFloat(read("location22","value2"))) / Math.pow(10,6)
 
   var  IT_Sum1 = (E1 + E2)
   return IT_Sum1 }}

 while(1) {     
 var sum1 = sum()
 var sum2 = sum1()  
 var IT_delta = sum2 - sum1 
 sleep(3.6 * 1000000)}

I have experimented with different placements of the setTimeout function within the code, but I am struggling to get sum2 to wait for the delay. Any suggestions for a more efficient way to calculate the subtraction of the same data in hourly loops?

Answer №1

One way to analyze the array is by adding values each hour and then determining the difference between adjacent indexes.

To execute code every hour, you can utilize window.setTimeout and specify a callback function along with the time interval.

// array containing hourly added values
var numbers = [];
function runHourly() {
 var dateNow = new Date();
 var mins = dateNow.getMinutes();
 var secs = dateNow.getSeconds();
 var interval = (60*(60-mins)+(60-secs))*1000;
 if (interval > 0) { 
    window.setTimeout(runHourly, interval);
 }
 // include your delta calculation logic here
 numbers.push(calculateDelta());

 if(numbers.length >= 2) {
    var hourlyDelta = numbers[1] - numbers[0];
    // perform actions based on delta value
    // adjust array to capture delta of new hourly values
    numbers.shift();
    
 }
}

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

Latest versions of Bootstrap are facing issues with the functionality of the Carousel feature

I'm struggling to create a basic carousel, but for some reason, it's not functioning properly. I attempted to use the sample code provided by Bootstrap's documentation, but it doesn't behave as expected (slides won't transition and ...

Colorbox: Display a specific section from a separate HTML page

Currently, I am facing a challenge where I need to open just one specific part of an external HTML page in a colorbox. I attempted the following approach, however it is opening the entire page instead of just the specified part (at the div with id="conten ...

Top method for determining available space for images positioned randomly within a specified area

Currently, I am utilizing HTML's Canvas tag to design a word cloud that is randomly generated. My main focus is on finding the most effective way to determine where there is sufficient blank space within a specified area to accommodate a word. At the ...

Feeling lost on how to utilize .map, .reduce, or foreach in my code

Recently delving into JavaScript, I find myself a bit perplexed despite scouring through various answers and resources on Mozilla.org. My struggle lies in seamlessly using .map and .filter on straightforward arrays, but feeling a bit lost when it comes to ...

How to extract keys with the highest values in a JavaScript hashmap or object

Here is an example for you to consider: inventory = {'Apple':2, 'Orange' :1 , 'Mango' : 2} In this inventory, both Apple and Mango have the maximum quantity. How can I create a function that returns both Apple and Mango as t ...

computational method for organizing balls in a circular formation

I need help arranging 10 spheres in a ring using code. So far, this is what I have, but it's not working as expected. const sphereGeometry = new THREE.SphereGeometry(300, 20, 20); const sphereMaterial = new THREE.MeshLambertM ...

Handling onChange events for several typescript <Select> elements

As a non-TS developer, I'm delving into the realm of multiple selects and dropdown menus with Material-UI's select component. Progressing from a basic setup, I successfully implemented a single select but now face a challenge in adding another dr ...

Exploring the elements of Ext.js gridpanel and content components

Currently, I am diving into the world of Ext.js and finding it to be quite distinct from the asp.net ajax library despite some initial similarities. My goal is to populate a grid with test data formatted in JSON. The code snippet below illustrates my atte ...

Troubleshooting Intel Edison application update issues

After setting up the IoT XDK, I decided to try out the blink example. Excitedly, I saw that the LED on pin 13 was blinking just as expected! But when I attempted to change the interval from 1000ms to 100ms and 3000ms, there was no difference in the blinkin ...

Transfer the selected user content from one canvas to another

After successfully implementing a simple selection area on canvasA, I encountered an issue with copying the area to canvasB. The user is supposed to select an area and then see that selection appear on another canvas once they finish making the selection b ...

The React-Toastify module is missing

Having issues with react toast plugin displaying an error. Prior to attempting to use the toast feature, I executed this command: npm install --save react-toastify The following error is being shown in Google Chrome Console: ERROR in ./src/Pages/Login ...

Nested mapping of objects in a mapped object

I'm attempting to iterate through an array within another array that has already been iterated My objective is to display the userName and products each user has. To achieve this, I first map the main data array to show the userName of each object. ...

The use of a script redirect in PHP can result in a recursive

Hey there, I'm a new rank newbie here! So I have this code that's supposed to redirect users to the relevant page on both mobile and desktop. But it seems like it's causing a never-ending loop with the webpage constantly reloading. Should I ...

A guide on updating table rows in Material UI and React Table

I am currently developing a table using Material UI/React that consists of multiple text fields per row and permits users to delete specific rows. Each row in the table is generated from a list, and I am utilizing React's state hooks to manage the sta ...

Loop through each item using the .each() method, then make an AJAX

I need the "done." text to show up only after all the tasks within my each() function have completed. Despite attempting to use a delay, it seems that they are running asynchronously and the "done." message displays too early. Additionally, I am sending ...

Tips for successfully installing a package through npm

Looking to set up nest.js Using the guide provided below. https://www.npmjs.com/package/@nestjs/cli Attempted the following command $ npm install -g @nestjs/cli Encountered this error message. bash: /usr/local/bin/npm: No such file or directory Any ...

Unable to locate the variable named StyleSheet

I've been delving into React Native using this informative site https://www.tutorialspoint.com/react_native/react_native_animations.htm However, I encountered a setback when attempting to launch the app on my iPhone. An error message indicates that a ...

Showing AngularJS information on Views

After successfully implementing static HTML with views, as shown in this example: https://embed.plnkr.co/MJYSP01mz5hMZHlNo2HC/ I am now facing a challenge with integrating the angular-ui accordion within ng-view. You can view the accordion I am attemptin ...

Click outside of this popup to dismiss it

I have been struggling to figure out how to make this popup close when clicking outside of it. Currently, it only closes when clicked directly on it. Your assistance in this matter is greatly appreciated. Here is the HTML code: <h2>Popup</h2> ...

What is the reason for browsers changing single quotation marks to double when making an AJAX request?

Jquery: var content = "<!DOCTYPE html><html lang='en'><head><meta charset='utf-8'><meta http-equiv='X-UA-Compatible' content='IE=edge'><meta name='viewport' content='w ...