Reputation: 867
Okay, I'm totally confused. I'm sure this is a scoping or a closure thing, but could someone explain why
$(document).ready(function() {
var test = 0;
var whatev = [1,2,3,4,5];
$.each(whatev, function(i, v) {
test += 1;
});
alert(test);
});
alerts "5" and
$(document).ready(function() {
var test = 0;
var whatev = [1,2,3,4,5];
$.each(whatev, function(i, v) {
$.ajax('http://example.com/').done(function(data) {
test += 1;
});
});
alert(test);
});
alerts 0? Why does the anonymous function in the $.each
call have access to test but the anonymous function for the ajax call doesn't? Where is that anonymous function being defined?
Upvotes: 0
Views: 862
Reputation: 17906
you could work with callbacks, everything will wait for
the loop waits for ajax callback and the alert waits for finishing the loop
function request(callback){
$.ajax('http://example.com/').done(function(data) {
callback();
});
}
var y = 0;
function loop(whatev,callback){
request(function(){
test += 1;
y++;
if(y >= whatev.length){
//stop looping and trigger callback (alert)
callback();
}else {
loop(whatev);
}
});
}
$(document).ready(function() {
var test = 0;
var whatev = [1,2,3,4,5];
loop(whatev,function(){
alert(test);
});
});
Upvotes: 0
Reputation: 2471
The callback of JQuery each
is synchronous.
The callback of JQuery Ajax (asynchronous javascript and xml) however is asynchronous.
If you want the ajax function to be synchronous you can do it as such:
$.ajax({
type: "GET",
url: "http://example.com/",
async: false
})
Upvotes: 2
Reputation: 61401
That is because
$.ajax('http://example.com/').done();
is asynchronous.
function(data) {
test += 1;
}
is being called after all the code has been executed.
Upvotes: 2