The following javascript displays the final result (instead of updating every second). How can I iterate through the result of the getJSON call, display that result, and delay until I display the next element?
function display(state) {
for (var i=0; i < state.length; i++) {
$('#someDiv' + i).text(state[i]);
}
}
$.getJSON('/getdata', function(data) {
$.each(data, function(key, val) {
setTimeout(function(){display(val)}, 1000);
});
}
The problem is that in your
$.each()loop you queue all the timeouts at once, all for 1000ms after the loop. The simplest way to fix that is as follows:Noting that that will only work if
datais an array and thuskeyis the integer index. Ifdatais an object andkeyis not an integer index you could do this:(Set
ito 1 initially if you don’t want the first update to happen immediately.)