You could use the Promise API of jQuery to chain up the requests.
Whenever on request is finished the queryYears
is called another time with the year
incremented by one, until year
is larger then maxYear
function queryYears(year, maxYear) {
// check if the year is less or equal maxYear
if (year <= maxYear) {
return $.ajax({
url: 'calendar.php?year=' + year,
beforeSend: function() {
console.log('Loading year: ' + year);
}
})
.then(function(result) {
$('#events').append(result);
//incremenat year by one
year++;
//only call queryYears if year is less or equal to maxYear
if (year <= maxYear) {
return queryYears(year, maxYear);
}
})
} else {
// if not return a rejected Promise
return Promise.reject(new Error(year + ' is larger then ' + mxYear))
}
}
queryYears(2000, 2017)
.then(function() {
console.log('finished')
})
.catch(function(err) {
console.log('failed with: ')
console.dir(err)
});