Reputation: 1191
The following code requests json data from a URL. Once it has that data, it runs an .each function for each element in the json data. For examples sake, I have reduced the .each function to simply doing a document.write with each value from the json and alerting "finished" after it is over.
If I remove the setTimeout, then the code works as it should, first finishing all of the .each commands and then alerting finished. However, with the setTimeout, it alerts finished before it ever executes all of the .each commands.
I have the delay itself working perfectly, however the code AFTER the initial delay executes immediately, not waiting for all of the .each commands to execute. Here is the code:
$.ajax({
type: "GET",
url: 'url to json data',
dataType: "json",
success: function(data) {
var time = 10;
$.each(data, function(key, val) {
setTimeout(function() {
document.write(val.term);
return;
}, time); time += 10;
});
alert('finished');
},
error: function () {}
})
How can I keep the delay while iterating through the .each commands and only when it is finished iterating through all of the .each commands, alert 'finished'?
Upvotes: 0
Views: 83
Reputation: 227200
What you can do is use jQuery's deferreds here. Use a promise, then call a callback when it's all done.
Untested, but you can do something like this:
$.ajax({
type: "GET",
url: 'url to json data',
dataType: "json",
success: function(data) {
var time = 10,
timeouts = [];
$.each(data, function(key, val) {
var def = new $.Deferred;
timeouts.push(def);
setTimeout(function() {
console.log(val.term);
def.resolve();
}, time);
time += 10;
});
$.when.apply($, timeouts).done(function(){
alert('finished');
});
},
error: function () {}
})
Upvotes: 3
Reputation: 16184
You could put the alert in a setTimeout too but reset it on each iteration so that it only runs when the each
has successfully completed.
$.ajax({
type: "GET",
url: 'url to json data',
dataType: "json",
success: function(data) {
var time = 10;
var t=setTimeout(function(){alert('finished');} , 20);
$.each(data, function(key, val) {
setTimeout(function() {
//document.write(val.term);
clearTimeout(t);
t=setTimeout(function(){alert('finished');} , 20);
return;
}, time); time += 10;
});
},
error: function () {}
})
Upvotes: 1