EaBangalore EaBangalore - 29 days ago 9
Javascript Question

how to keep track of array index during ajax call

i have array like this

urls = ['url1','url2','url3'];
how can i keep track of array index so, that on every
Ajax
call i can delete one element.

here is something i'm trying



var my_delay = 2000;
var urls = ['url1','url2','url3'];


$(function() {
callAjax();
});


function callAjax() {
/*$.ajax({
// my ajax params ..............
success: function(data){
if(urls.length != 0){
console.log('must be called only 3 times');
setTimeout(callAjax, my_delay);
urls.shift();
}
}
}); */
console.log('must be called only 3 times');
console.log('in real situation i will going to use above commented ajax code');
if(urls.length != 0){ // stop here but you are not stoppping why?
setTimeout(callAjax, my_delay);
urls.shift();
} // end of if
}

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.0.3/jquery.min.js"></script>





Question: i want to stop the ajax call when there is no element in
urls[]
please keep in mind
ajax
is going to call
php page
in that scenario also i want to keep track on
array index

Answer

Use a global variable and a recursive function

var i = 0;
callAjax(urls[i]);
function callAjax(url) {
 $.ajax({
 url:url,
 success:function() {
if (i< urls.length)
   i++;
   callAjax(urls[i]);
 }
});
}