Preserve the existing value and then check it against the updated value of a variable within JavaScript

I utilized an API that supplies me with information in JSON format, retrieved the price of a specific currency, and presented it on a screen using JavaScript. I encapsulated this process within a function that dynamically updates the information at set intervals.

Now, I am looking for a piece of code that can compare the current price value against the next value received. If the new price is higher than the previous one, I want to either change the background color to green or trigger an alert. Conversely, if the new price is lower than the previous one, I would like the background color to switch to red.

Here's the snippet from my existing code:

var auto_refresh = setInterval(
  function() {
    var xmlhttp = new XMLHttpRequest();
    xmlhttp.onreadystatechange = function() {
      if (this.readyState == 4 && this.status == 200) {
        var myObj = JSON.parse(this.responseText);
        document.getElementById("bids1").innerHTML = myObj.BTCUSDT['bids']['0']['0'];
      }
    };
    xmlhttp.open("GET", "all.json", true);
    xmlhttp.send();

  }, 1000);

Answer №1

Avoid using intervals with Ajax requests

let value = 0;
const bidsData = document.getElementById("bids1");

function fetchData() {
  fetch('all.json')
  .then(response => response.json())
  .then(data => {
    const newValue = myObj.BTCUSDT['bids']['0']['0'];
    bidsData.innerHTML = newValue
    bidsData.classList.toggle("green",value > newValue)
    bidsData.classList.toggle("red",value < newValue)
    value = newValue;
    setTimeout(fetchData,1000)
  })
}  
fetchData()

Answer №2

Clarification

To ensure accuracy, it is advisable to review mplungjan's response above for a more precise method. Although incorporating the variable as instructed is an effective approach, the current method of regularly retrieving data is not recommended and should be revised in accordance with mplungjan's advice.

Suggested solution

It is generally suggested to utilize a global variable (or outside of the function scope) to store the current price and compare this value with the retrieved one.

// initialize current price
let currentPrice = 0;

var auto_refresh = setInterval(function () {
    var xmlhttp = new XMLHttpRequest();
    xmlhttp.onreadystatechange = function () {
        if (this.readyState == 4 && this.status == 200) {
            var myObj = JSON.parse(this.responseText);
            
            let newPrice = myObj.BTCUSDT['bids']['0']['0'];

            if (newPrice > currentPrice) {
                // perform some action like alerting or updating other attributes

            }

            // update the global variable and HTML display
            currentPrice = newPrice;
            document.getElementById("bids1").innerHTML = currentPrice;
        }
    };
    xmlhttp.open("GET", "all.json", true);
    xmlhttp.send();

}, 1000);

Depending on your specific needs, you can also conduct different checks and comparisons within the http request handler.

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

Is there a way to dynamically change an icon based on certain conditions using typescript?

I am struggling with displaying icons in my TypeScript code using Material Icons. I need to dynamically change the icon based on a condition, for example if the power is false I want to display 'power_off', but if it's true then I want to di ...

Manipulate paths in JS/JQuery by dynamically adding parameters with an indefinite number of values

My JavaScript script relies on an AJAX call that adds a parameter to an HTML request, but I've encountered two issues. I'm struggling to find a straightforward method to retrieve the pathname with parameters. With pure JavaScript, location.path ...

PHP does not detect the Ajax object that has been sent to it

Here's the data I am trying to send: In this blockquote: switch=rssAdd&data=[object Object],[object Object]... etc. This data is generated by the following code snippet: The Javascript function shown above parses XML elements and formats them ...

Updating the value of each preceding sibling of every checked checkbox using jQuery upon form submission

After extensive research, I discovered that the most effective approach involves using a clever workaround to capture every tick and untick on a dynamic input row with multiple checkbox arrays. However, none of the solutions provided a viable method. I th ...

Utilizing JSON Arrays to extract data and create three distinct arrays

I am currently working on extracting three arrays from the JSON Data retrieved from my restaurant. These arrays will represent categories such as Entre, Main, and Dessert, and will be displayed in a tableView Object. Below is the code snippet I am using to ...

Adjust the position of the object in relation to its current orientation

I am facing a challenge in moving an object upwards in relation to its current direction. I am working with a CubeGeometry that has a specific height, and my goal is to place an object at the top of it and have it rotate along with the cube. Simply adding ...

The WebDriverIO browser.Click function encountered difficulty locating an element while using Chrome, but it is functioning properly on Firefox

Currently, I am utilizing WebdriverIO in combination with CucumberJS for testing purposes. The following code functions correctly in Firefox; however, I encounter errors in Chrome which display element is not clickable. I am seeking a solution using JavaSc ...

Using PHP, Ajax, and JavaScript, display interactive data from the server in a dynamic modal popup listbox within a Tinymce-WordPress

Currently, I am in the process of developing a WordPress plugin using TinyMCE. The main functionality involves a button that triggers a popup modal with some list boxes. These list boxes need to be populated with values fetched from the server. To accompli ...

Learn how to utilize a Library such as 'ngx-doc-viewer2' to preview *.docx and *.xlsx files within the application

After 3 days of searching, I finally found a solution to display my *.docx and *.xlxs files in my angular application. The API returns the files as blobs, so my task was to use that blob to show the file rather than just downloading it using window.open(bl ...

Getting rid of the <br> tag as well as the linked <span> element

I've been experimenting with creating dynamic forms. My latest project involves a text box, an 'Add' button, and a div. The idea is that whenever a user types something into the text box and clicks the Add button, that value should appear in ...

Choose a selection from dynamically loaded options using AJAX

I am working with a scope that contains customer information, including country and state. Some countries require users to select a specific state. If one of those countries is selected, the state options are loaded into an object and a dropdown menu is di ...

Is there a way to transform a six-digit input into a date format using vue/JavaScript?

I've explored various solutions for this issue, but they all seem to be backend-focused. What I need is a Vue/JavaScript method. I have a string containing IDs, with the first 6 digits representing the date of birth and the final 4 digits being a pers ...

The amazingly efficient Chrome quick find feature, accessible by pressing the powerful combination of Ctrl + F, ingeniously

Currently using Google Chrome version 29.0.1547.62 m. I've employed the CSS attribute overflow set to hidden on the parent element, which renders some of my DIV elements hidden from view. Additionally, these concealed DIV elements are adjusted in pos ...

The CSS popup box fails to reset its data after being closed, and the closure button does not effectively close the popup

I am having an issue with a login popup on my website. Whenever I fill in the login or registration information and then close the popup, the next time I open it, the input box still contains the previous data. How can I reset the popup to always open with ...

How can we best understand the concept of custom directives using the link method?

As a beginner in AngularJS, I am looking to implement an autocomplete feature for text input. My JSON data is stored in JavaScript and I need help simplifying the process. Can you provide me with a straightforward solution? The specific requirement is to ...

What is the reason for using a callback as a condition in the ternary operator for the Material UI Dialog component?

I am in the process of reconstructing the Material UI Customized Dialog component based on the instructions provided in this particular section of the documentation. However, I am unable to grasp the purpose behind using a callback function onClose conditi ...

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 ...

Upon loading the React Login page, the focus immediately shifts to the 'password' field rather than the 'username' field

I am currently in the process of building a login page using React. The code below is from my input.jsx file where I have imported Bootstrap components. import React from "react"; const Input = ({ name, label, value, onChange, error }) => { ...

Invoke the designated JavaScript function within a subordinate <frame>

Below is an example of the standard HTML structure for a parent page named "index.html": <html> <head> <title>test title</title> </head> <frameset cols="150,*"> <frame name="left" src="testleft.html"> ...

When a Vue.js Directive is inserted or bound, it actually takes precedence over the click event

Imagine having multiple dropdowns or elements on the page that all utilize a directive called "closable". This directive triggers an expression if the element clicked is outside of the element using the directive. The intended behavior is that when clicki ...