Possible Duplicate:
passing index from for loop to ajax callback function (javascript)
I'd like to delay the i++ until the jquery callback is done. i have this:
for (var i = 0; i < stocks.length; i++) {
var lastprice = 0
var stock = stocks[i].stock;
$.getJSON('http://query.yahooapis.com/v1/public/yql?q=select%20*%20from%20yahoo.finance.quotes%20where%20symbol%20in%20("' + stock + '")&format=json&env=store%3A%2F%2Fdatatables.org%2Falltableswithkeys',
function(data) {
lastprice = data.query.results.quote.LastTradePriceOnly;
}).done(function() {
console.log(stock, lastprice);
});
};
and the problem is the loop finishes before the .getJSON does, and so I just end up console logging the last stock in my array, but the prices of all the stocks in my array. I tried this but it just kills my browser:
for (var i = 0; i < stocks.length;) {
var lastprice = 0
var stock = stocks[i].stock;
$.getJSON('http://query.yahooapis.com/v1/public/yql?q=select%20*%20from%20yahoo.finance.quotes%20where%20symbol%20in%20("' + stock + '")&format=json&env=store%3A%2F%2Fdatatables.org%2Falltableswithkeys',
function(data) {
lastprice = data.query.results.quote.LastTradePriceOnly;
}).done(function() {
console.log(stock, lastprice);
i++;
});
};
Anyone know what I'm doing wrong? Thanks!