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

Incorporating Dynamic Javascript: A Step-by-Step Guide

I came across a select object that looks like this: <select id="mySelect" onchange = "start()" > <option>Apple</option> <option>Pear</option> <option>Banana</option> <option>Orange</option> < ...

What steps do I need to take to extract the date and month from a single datepicker using the code below?

<div class="col-md-3 pull-left" style="padding:9px"> <input type="text" id="datepicker" class="form-control"> </div> The HTML and C ...

What methods can be used to maintain the selected date when the month or year is changed in the react-datepicker component of reactjs?

At the moment, I am using the Month selector and Year selector for Date of Birth in the react-datepicker component within a guest details form. The current functionality is such that the selected date is highlighted on the calendar, which works fine. How ...

Improprove the Express Router in a Node.js application

Is there a way to avoid repeating the isUserAuth and isAdminAuth middleware on each endpoint? Can I apply them just once so they work for all routes without having to specify them individually? const { createBranch, getAllBranch, getBranch } = require(&apo ...

What is the best way to compare JavaScript arrays with the same items but in a different order?

Within my product groups, each group is identified by a set of product_type_ids. I am looking for a way to match different groups based on their product_type_ids. The order of the ids may vary within the group, but as long as the sets of ids match, I cons ...

Display outcomes for chosen checkboxes

When I call the API: $url = 'https://plapi.ecomexpress.in/track_me/api/mawbd/?awb=awbnumber&order=' . $orderrecords[$k]["order_id"] . '&username=admin&password=admin123';, I retrieve the status results of all Order IDs and d ...

Using Highmaps with PHP and JQuery Ajax: Passing a parameter to the current page and retrieving it with PHP

I have successfully created a map using PHP and Highmaps (from Highcharts libraries) that retrieves data from a SQL Server database. Everything is working smoothly so far! However, I am now facing the challenge of sending a value from the map to another PH ...

Vue.js - encountering an issue with undefined response data

Greetings! I've encountered a script issue while trying to submit a form in VUE. The error message displayed in the developer panel states: "TypeError: error.response.data.errors is undefined". As a newcomer to Vue, I'm seeking some assistance as ...

Issue with jQuery week calendar: Existing data not loading correctly into the calendar

I am currently experimenting with the jQuery week calendar plugin found at https://github.com/themouette/jquery-week-calendar/wiki in order to showcase meetings on my website. However, I am encountering an issue where my events.php file is returning JSON d ...

Cross-origin resource sharing problem arises when JavaScript is loaded asynchronously using script tags created dynamically

By dynamically creating a script as shown below, the JavaScript source is downloaded asynchronously. let newScript = document.createElement('script'); newScript.src = srcUrl; let firstScript = document.getElementsByTagName('script')[0] ...

Change a space-separated string containing coordinates into an array of JavaScript objects

Here is a string separated by spaces: const coordinates = "42.44492,75.637764 42.445503,75.64534 42.433681,75.6604" Now, we want to convert it into an array of objects: const coordinatesArray = [ { lat: 42.44492, lng: 75.637764 }, { lat: 42.4455 ...

What are the steps for retrieving a JSON object within an array?

var jsonData = '[{"type":"product","id":1,"label":"Size","placeholder":"Select Size","description":"","defaultValue" :{"text":"Size30","price":"20"},"choices":[{"text":"Size30","price":"20","isSelected":"true"},{"text" :"Size32","price":"22","isSelec ...

Missing transitive dependencies have been identified within the node_modules directory when using npm

In my software development journey, I am working on two npm projects - one called X and the other called Y. Let's say that X relies on angular and has it specified as a dependency in its package.json file. To establish a connection between X and Y, I ...

filling in a label with options from a listbox using panels or a modal popup

I have implemented a listbox that is populated from a database. The listbox appears using modal popup and panels when the button labeled select user is clicked. However, I am facing an issue where, upon selecting a specific user from this list and clicking ...

Generating binary payload with Node-RED

Recently started with node-red and javascript. I am looking to establish a connection with a relay controller for status using the TCP input. I have configured a function node to create a two-byte request which will be sent through the TCP input node to th ...

WordPress now features the ability to toggle both parent menu items when clicked, providing a more streamlined user experience

I am currently facing an issue with a menu structure, where parent menu items have submenus that need to toggle on click. However, I am encountering a problem where, upon placing the code inside a forEach loop, both submenus toggle instead of only togglin ...

What are the steps to resolve the "undefined cannot read property push" error in Node.js?

While attempting to learn Nodejs, I created a simple app. However, when I run "nodemon index.js" in the command prompt, I encountered the following error: TypeError: Cannot read property 'push' of undefined The app crashed and is now waiting for ...

Querying through a database containing 1 million <string Name, int score> pairs efficiently within sub-linear time

My JSON object holds 1 million pairs. var student = {[ { name: "govi", score: "65" }, { name: "dharti", score: "80" }, { name: "Akash", score: "75" },............. up to a million ...

Benchmark reveals that JSON encoding is faster than Avro encoding in PHP

Despite the widespread belief that Avro encoding is faster than JSON, my personal tests yielded surprising results. In all of my experiments, JSON consistently outperformed Avro by a significant margin. Could I be overlooking something crucial in my analys ...

How can I convert the left links in my navigation bar to a CSS drop-down menu to make it more responsive on small screens?

Here is the structure of my HTML (at the top): <!DOCTYPE html> <html> <head> <meta charset="utf-8"> <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.4.8/angular.min.js"></s ...