简体   繁体   中英

Set global variable within anonymous function

I want to query a value from a script and use the value as variable for further functions. This code returns zero despite a value is set.

var total = 0;
var jqxhr = $.getJSON("number.php?jsonp=?", function(data) {
    total = data[0]['Total']; // e.g 1234567
});
alert (total); // gives zero

I read that the problem could be with the asynchronous call and that my alert is executed before the anonymous function. I also tried to use some kind of setter function but withous success.

How can I set the global variable total ?

Edit:

I now tried to use deferred objects / promises. I still have the problem that I need the value from the AJAX call before I initialise my counter. I cannot create the counter object in the done section because I cannot later change the value of the counter (still no global variable). Currently I have this:

var counter = $('.counter').jOdometer({
    counterStart: '0',
    numbersImage: '/img/jodometer-numbers-24pt.png', 
    widthNumber: 32,
    heightNumber: 54,
    spaceNumbers: 0, 
    offsetRight:-10,
    speed:10000,
    delayTime: 300,
    maxDigits: 10,
});

function update_odometer() { 
    var jqxhr = $.getJSON("/number.php?jsonp=?")
        .done(function(data){
            console.log(data);
            total = data['Total'];
            counter.goToNumber(total);
        })
        .fail(function(data){
            console.log(data);
        });
};

update_odometer();
setInterval(update_odometer, 60000);

If I initialize the counter with zero then there is a strange start animations which jumps up and down. If I could get the real number instead of zero everything would work fine. Or should I completely switch to a synchronous call? How would I do that? Or are callbacks the better solution?

Took me a while to understand your problem. Still I'm not sure whether this would help or not.

var counter = null;
function update_odometer() {
    var xhr = $.getJSON("/number.php?jsonp=?").done(function(data) {
        if (counter === null) {
            var counter = $('.counter').jOdometer({
            counterStart: data['Total'],
            numbersImage: '/img/jodometer-numbers-24pt.png', 
            widthNumber: 32,
            heightNumber: 54,
            spaceNumbers: 0, 
            offsetRight:-10,
            speed:10000,
            delayTime: 300,
            maxDigits: 10,
            });
        } else {
            counter.goToNumber(data['Total']);
        }
    });
}

If I were you I would look into library code and rectify the strange animation for zero start value. And I understand that you are not afraid to do that.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM