Skip to content Skip to sidebar Skip to footer

Variable Becomes Nan When I Try To Use It Outside Of The .each Function

I'm grabbing a JSON obj from an external source. It appears as so: {'total':16231642,'totalamount':437442282.55} I set it as a global var, set it in the each function and then try

Solution 1:

Remove var key word inside if statement var todaystart;

 if (key == 'totalamount')
            {
                todaystart = val; //was using parseFloat before to ensure that the datatype was correct, in case anybody answers that.
                //alert(todaystart);                
            }

Your full code will be

$(document).ready(function () {
    var todaystart;
    //Get vals from JSON txt
    $.getJSON("proxy.php", function (data) {
        $.each(data, function (key, val) {
            if (key == 'totalamount') {
                todaystart = val; //was using parseFloat before to ensure that the datatype was correct, in case anybody answers that.
                //alert(todaystart);                
            }
        });

        calcualtion();


    });

});

function calcualtion() {

    var avgvol = 18556;
    var price = 26.95;
    var avg = avgvol * price;
    alert(todaystart);
    var avgpls = todaystart + avg;

    var numAnim = new countUp("totalmon", todaystart, avgpls, 0, 86400);
    numAnim.start();

    //Sess Earned       
    remavgpls = avgpls - todaystart;
    var nu2Anim = new countUp("sessmon", 0, remavgpls, 0, 86400);
    nu2Anim.start();
    //Sess Time     
    var nu3Anim = new countUp("minmon", 0, 86400, 0, 864000);
    nu3Anim.start();
}

NOTE: Move the calculation code inside getJSON method bcoz getJSON is Asynchronous function


Solution 2:

You are re declaring the variable 'todaystart' each time the loop opens, which should be avoided. Never ever create a variable inside loops, instead make it as a global variable, to increase the client-side performance.


Post a Comment for "Variable Becomes Nan When I Try To Use It Outside Of The .each Function"