Nick Nick - 11 months ago 68
jQuery Question

Using interval in AJAX callback, variable not updating

I am able to successfully retrieve data using the

get_data()
function inside a
setInterval
. However, when the AJAX function finds a new price, calling the
get_data()
function does not return the new price, but continues to return the price given on its first iteration (explained by the two console log lines)

How can I have the price updated properly when calling
get_data()
inside an interval?

// Collect price data into array
var interval = 1000;
var arr = [];

function price() {
setInterval(function() {
get_data(function(result) {
arr.push(result);
console.log('updated price: ' + arr[0]); // not updated correctly
});
}, 1000);

function get_data(callback) {
$.ajax({
url: 'http://' + domain + '/site-options/',
dataType: 'json',
cache: fase,
success: function(data) {
var price = data['gbp_price'];
var abs_change = data['gbp_abs_change'];
var p_change = data['gbp_change'];
var market_cap = data['gbp_market_cap'];
var today_max = data['gbp_today_max'];
var today_min = data['gbp_today_min'];

var obj = {
'price' : price,
'abs_change' : abs_change,
'p_change' : p_change,
'market_cap' : market_cap,
'max' : today_max,
'min' : today_min
};

console.log('price: ' + price); // updated correctly

if (callback)
callback(obj);
}
});
}
}
price();

Answer Source

When pushing data into an array stack it will at it to the end. You are then logging the first value each time so you can either avoid .push()-ing and just run:

console.log( result.price );

or:

console.log('updated price: ' + ( arr.length - 1 ) );