jQuery uploads elements only when the page is initially loaded for the first time

The issue seems to be related to the

$(document).ready(function() {});
code block or potential misuse of callbacks.

My goal is to execute getTotalMarketCap(), getAllOtherValues(), and getMarketShare() in sequence for an accurate market share calculation. However, the market share update in the table is delayed by 60 seconds.

Check out the code here: https://codepen.io/anon/pen/wjYJgW

While my initial reason for this post was to address the bug, I also welcome suggestions for enhancing the overall code quality. What improvements can be made?

Answer №1

Here is a suggested solution:

// Formats numbers with commas.
String.prototype.commafy = function()
{
    return this.replace(/ (^|[^\w.])(\d{ 4,})/ g, function($0, $1, $2) {
        return $1 + $2.replace(/\d(?= (?:\d\d\d) + (? !\d))/ g, "$&,");
    });
};

/**
 * Rounds decimals.
 * @param {number} num - The number to round...
 * @param {number} scale - How many decimal places?
 */
function fixed (num, scale) {
  return (+(Math.round(+(num + "e" + scale)) + "e" + -scale)).toFixed(scale);
}

// Declare variables
var totalCap;
var totalCapTemp;
var bitcoinPriceTemp;
var bccPriceTemp;
var bitcoinMarketCap;
var bccMarketCap;
var bitcoinMarketCapTemp;
var bccMarketCapTemp;
var bitcoinMarketShareTemp;
var bccMarketShareTemp;
var bitcoinMarketShare;
var bccMarketShare;
var bitcoinVolTemp;
var bccVolTemp;
var bitcoinChangeTemp;
var bccChangeTemp;
var bitcoinTxTemp;

var chart;
var myVar = setInterval(myTimer, 60000);

// When document is ready
$(document).ready(function() {
    myTimer();
});

// Function to run in order
function runInOrder(callback)
{
    getTotalMarketCap(function() {
        getAllOtherValues(function() {
            getMarketShare(callback);
        });
});
}

// Get total market cap
function getTotalMarketCap(callback)
{
    $.getJSON("https://api.coinmarketcap.com/v1/global/", function(json) {
        // Processing data
        totalCap = fixed (parseFloat(json.total_market_cap_usd / 1000000000), 2);
        // Display data on the page
        if (!totalCapTemp || totalCapTemp == totalCap)
        {
            $("#totalCap")
            .text("$" + totalCap + "B")
            .removeClass();
        }
        else if (totalCap > totalCapTemp)
        {
            $("#totalCap")
            .text("$" + totalCap + "B")
            .removeClass()
            .addClass("green");
        }
        else
        {
            $("#totalCap")
            .text("$" + totalCap + "B")
            .removeClass()
            .addClass("red");
        }
        totalCapTemp = totalCap;
        callback();
    });

}

// Get all other values
function getAllOtherValues(callback)
{
    // Process data
    var lastInstruction = function(){
    // Get data from API
    $.getJSON("https://api.blockchain.info/stats?cors=true", function(json) {
            // Process Bitcoin transactions
            bitcoinTx = json.n_tx.toLocaleString();
            // Display Bitcoin transactions
            if (!bitcoinTxTemp || bitcoinTxTemp == bitcoinTx)
            {
                $("#bitcoinTx")
                .text(bitcoinTx)
                .removeClass();
            }
            else if (parseInt(bitcoinTx) > parseInt(bitcoinTxTemp))
            {
                $("#bitcoinTx")
                .text(bitcoinTx)
                .removeClass()
                .addClass("green");
            }
            else
            {
                $("#bitcoinTx")
                .text(bitcoinTx)
                .removeClass()
                .addClass("red");
            }
            bitcoinTxTemp = bitcoinTx;
            callback();
        });
    };

    // Get data from API
    $.getJSON("https://api.coinmarketcap.com/v1/ticker/?limit=10", function(
        json
    ) {
        // Process data for Bitcoin and Bitcoin Cash
        // Display data on the page
        $.each(json, function(index, value) {
            if (value.id == "bitcoin")
            {
                // Bitcoin processing
            }

            if (value.id == "bitcoin-cash")
            {
                // Bitcoin Cash processing
            }

            if (index >= json.length - 1)
                lastInstruction();

        });
    });


}

// Get market share
function getMarketShare(callback)
{
    // Calculate Bitcoin market share
    // Display Bitcoin market share on the page
    // Update chart if needed

    // Calculate Bitcoin Cash market share
    // Display Bitcoin Cash market share on the page
    // Update chart if needed

    callback && callback();
}

// Create chart
function createChart()
{
    $(function() {
        Chart.defaults.global.legend.display = false;
        Chart.defaults.global.animation.duration = 0;
        var ctx = document.getElementById("myChart").getContext("2d");
        $("#myChart").css("background-color", "#222428");

        // Create a doughnut chart
        chart = new Chart(ctx, {
            type: "doughnut",
            data: {
                labels: ["Bitcoin", "Bitcoin Cash", "Others"],
                datasets: [
                    {
                        label: "dataset",
                        backgroundColor: ["#2196f3", "#f44336", "#FFFFFF"],
                        borderColor: "#000000",
                        data: [
                          bitcoinMarketShare,
                          bccMarketShare,
                          fixed (100 - bccMarketShare - bitcoinMarketShare, 2)
                        ]
                    }
                ]
            },
            options:
                {
                    cutoutPercentage: 70,
                    rotation: 185
                }
        });
    });
}

Make sure to call the callback inside $.getJSON's success handler

Answer №2

Have you considered employing setTimeout to manage the refresh rate of your code? It could help establish a consistent pattern for updates.

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

Changing global properties in VueCli

Recently, I integrated a component library into my Vue 3 project. All instances of the component require the same styles. Instead of manually adjusting each instance's props, I opted to utilize a global property: app.config.globalProperties.$tooltipS ...

Transforming a typical JSON file into a parent-child hierarchical JSON structure similar to the one utilized in d3's flare.json file format

My JSON file has a specific structure: { "a": "b", "c": "d", "e": { "f": "g", "h": "i" } } I want to transform it into the following structure: { "name": "Root", "parent": "null", "children": [ { ...

What sets $vm.user apart from $vm.$data.user in Vuejs?

When you need to retrieve component data, there are two ways to do so: $vm.user and $vm.$data.user. Both methods achieve the same result in terms of setting and retrieving data. However, the question arises as to why there are two separate ways to access ...

Determine if an element from the first array is present in the second array

I've encountered a challenge while building a simple react app and I could use some help. The Problem at Hand :- My goal is to compare items in firstArray (which contains separate dictionaries) with those in secondArray. While the loop for checking ...

Encountering issues in parsing JSON for PhoneGap Application

I've been struggling with parsing JSON data for a unique PhoneGap application that is dynamically generated by a localStorage variable. The PHP script is functioning properly, but the JavaScript code seems to be encountering issues when trying to pars ...

Learning the process of using JavaScript to extract data from a JSON file containing arrays

Currently grappling with the challenge of reading a JSON file using JavaScript. Unsure if my JSON file is in the correct format with arrays, but here is what I have. [ { "passageNumber":"2.3.1", "title":"Inside and out: A bronze ...

Changing the height of tablerows in Material UI v5: A step-by-step guide

I am attempting to adjust the height of the rows in this material-ui code example. import * as React from "react"; import { styled } from "@mui/material/styles"; import Table from "@mui/material/Table"; import ...

What is the best way to create a slideshow that automatically starts upon loading and pauses when hovered over?

I have recently set up a div element for my slideshow. I've included a script to enable navigation using next and previous arrows. However, I am looking to add an automatic slideshow feature that stops on hover. As a beginner, I would appreciate any a ...

The item is not functioning properly as intended

After delving into the concepts of prototype and proto, I believed that I had grasped the concept. However, something doesn't seem to add up. Can someone shed light on why directly accessing an Object like this does not yield the desired outcome? fun ...

Encountering a problem when utilizing the each loop within an ajax request

While attempting to iterate through a each loop within an Ajax call, I encounter the following error: TypeError: invalid 'in' operand e Here is my Ajax call code snippet: $.ajax({ type: "POST", url: "/admin/counselormanagem ...

What is the best method to make the first input field the focus in BootStrap?

Is there a way to prioritize the focus on the initial input element in an HTML form without specifying an ID? How to set the focus to the first input element in an HTML form independent from the id? I'm working with BootStrap and ASP.NET MVC4. De ...

Differences between importing Component and Vue from "vue-property-decorator" versus importing Vue from "vue"

Can you explain the specific differences and scenarios where importing Vue from vue-property-decorator versus just vue would be applicable? I have learned that when defining a custom component with a @Component decorator, it is necessary to import Vue fr ...

Troubleshooting: Why isn't my CSS fixed position working for my sticky

I have a simple jQuery code snippet that is supposed to make the navigation element sticky by applying a class with position: fixed. However, I'm facing an issue on my Commerce platform where the fixed position property doesn't seem to work corre ...

Managing JSON data files in an Express application

I'm facing a challenge with file upload using express.js. I currently have this mongoose schema: { title: { type: String, required: true, min: 1, max: 1024, }, whatToRead: [{ type: String }], questions: [ { question: { ...

Incomplete JSON response being received

We set up an express server to call an API and successfully requested the JSON object in our server. However, we are facing an issue where the JSON data is getting cut off when being displayed as a complete object on the client side. We tried using parse i ...

How to use the window.confirm method to print the HTML tag in an AJAX post

Is there a way to display a confirmation window for users who want to delete data from the database without including HTML tags like <strong> or <br />? I am currently using the confirm() function as follows: var str = document.getElementById ...

Deciding on excluding empty key:value pairs from an object for various filtering needs

One of the features in my app allows users to filter results by "blood group" and "city", along with other areas. The information is retrieved from a database using Axios for Vuejs, incorporating query strings within the URL. For example: http://example.co ...

Leveraging various libraries in React

My query revolves around a React application where I have integrated Material UI for only two components. Despite installing the entire Material UI library, will this lead to an increased bundle size for my application? Or does the build process only inc ...

The useCallback hooks persist outdated values when the list is refreshed

Why am I not getting the expected values every time the function onRefresh is called using Hooks? Example when onRefresh is called twice: Expected values: true 0 20 false true 0 20 false Received values: false 0 0 false false 20 20 false Initial st ...

nodejs - pkg encountered an error: only one entry file or directory should be specified

I am currently facing issues with packing my simple cli node script using pkg. After running the command below: host:~ dev$ pkg /Users/dev/Desktop/myscript/ --target node14-macos-x64 node14-linux-x64 node14-win-x64 I encountered an error in the terminal: ...