0

How can synchrony be forced in a javascript loop?

This is without synchrony :

$.each(data, function(index, value) { 
  alert(index + ': ' + value); 
});

synchrony attempt :

var time = 500;
$.each(data, function(index, value) { 
  setTimeout(alert(index + ': ' + value), time);
  time += 500;
});

but so far all it does is run the alert in a row, without interval


This is the ajax request that I need to run in a QUEUE :

        $.each(data, function(key, val) {

            $.ajax({      
            url: 'ajax/getPerson.php', 
            type:'post',
            dataType: 'json',
            data: { 'dude' : val["idG"] },
            success: function(data) { createHTML.person(data) }
        }
coiso
  • 7,151
  • 12
  • 44
  • 63

3 Answers3

2

Try this:

var time = 500;
$.each(data, function(index, value) { 
  setTimeout(function() {
     alert(index + ': ' + value);
  }, time);
  time += 500;
});
dfsq
  • 191,768
  • 25
  • 236
  • 258
1

Pass the code you want to execute in a function() object as first argument to setTimeout(), like so:

var time = 500;
$.each(data, function(index, value) { 
  setTimeout(function() { alert(index + ': ' + value) }, time);
  time += 500;
});
Nelson
  • 49,283
  • 8
  • 68
  • 81
1

According to your comment:

I am using this function to make a DataBase Requests and they are not coming back in the order I ask for

The callback method is intuitive and rather easier to implement, but what if you have 100 request to be made? Assuming 200ms per response-time that's total of 20 second.

So here is the question: Do you really care about the returning order of AJAX calls or you just have to process the returning data by the order of calls you have fired?

If the answer is latter, the solution will be:

  1. fire all ajax calls at once ( or in queue )
  2. maintain an array of returning datas
  3. check array whether all requests have been successfully returned, re-request if there's an error ( or other error handling mechanism)
  4. when all requests are returned, do the data processing you originally intended
fin
  • 1,299
  • 1
  • 10
  • 20