0

I would like to add a 500ms pause between each iteration of the first $.each

I'm not sure how to apply this solution: How to add pause between each iteration of jQuery .each()?

to my particular case:

function iterateAddresses () {

  var time = 500;

  $.each( addresses_google, function( index, value ) {
    var service = new google.maps.DistanceMatrixService();

    service.getDistanceMatrix(
      {
        origins: [origin],
        destinations: value,
        travelMode: 'DRIVING'
      },
      callback
    );

    function callback(response, status) {
      var origins = response.originAddresses;
      var destinations = response.destinationAddresses;
      for (var i = 0; i < origins.length; i++) {
        var results = response.rows[i].elements;
        for (var j = 0; j < results.length; j++) {
          var element = results[j];
          if(element.status == "NOT_FOUND"){
            var distance = 0;
          } else {
            var distance = element.distance.value;
          }
          if(distance > radius){
            // Store postids in array
            postids_to_hide.push(
              addresses_postids[index][j]
            );
            // Hide elements where postid is in the postids_to_hide arrays
            $.each( postids_to_hide, function( index, value ) {
              $(".main_short_post_div").filter(function(){
                return $(this).attr('data-post-id') === value;
              }).hide();
            });
          } // end if d < r
        } // end for j
      } // end for i
    } // end callback function
  }); // end each addresses_google

}; // end iterateAddresses

iterateAddresses();
Community
  • 1
  • 1
Pim
  • 445
  • 1
  • 8
  • 24
  • 1
    Possible duplicate of [Applying delay between iterations of javascript for loop](http://stackoverflow.com/questions/11764714/applying-delay-between-iterations-of-javascript-for-loop) – Strelok Dec 13 '16 at 21:36
  • As you can see there's a whole bunch of code, function arguments and variables within my iterations. There lies my difficulty. – Pim Dec 13 '16 at 21:39
  • So add things to a collection, use a timeout and remove the items from the collection. – epascarello Dec 13 '16 at 21:43
  • Variables `from` and `to` are unused? – Ben Aston Dec 13 '16 at 22:37

2 Answers2

1

You could separate in other function called since your iterateAddresses() function

function iterateAddresses () {

  var time = 500;
  // Then get a random number between 500 and 599    
  $.each( addresses_google, function( index, value ) {
        var ram = Math.floor(Math.random() * (599-time+1)) + time;
        setTimeout( "OtherFunction("+index+","+value+");", ram);
  }); // end each google_address

}; // end iterateAddresses


function OtherFunction(index, value)
{
    var service = new google.maps.DistanceMatrixService();

    service.getDistanceMatrix(
      {
        origins: [origin],
        destinations: value,//addresses_google,
        travelMode: 'DRIVING'
      },
      callback
    );

    function callback(response, status) {
      var origins = response.originAddresses;
      var destinations = response.destinationAddresses;
      for (var i = 0; i < origins.length; i++) {
        var results = response.rows[i].elements;
        for (var j = 0; j < results.length; j++) {
          var element = results[j];
          if(element.status == "NOT_FOUND"){
            var distance = 0;
          } else {
            var distance = element.distance.value;
          }
          var from = origins[i];
          var to = destinations[j];
          if(distance > radius){
            // Store postids in array
            postids_to_hide.push(
              addresses_postids[index][j]
            );
            // Hide elements where postid is in the postids_to_hide arrays
            $.each( postids_to_hide, function( index, value ) {
              $(".main_short_post_div").filter(function(){
                return $(this).attr('data-post-id') === value;
              }).hide();
            });
          } // end if d < r
        } // end for j
      } // end for i
    } // end callback function
}

iterateAddresses();
edulego
  • 34
  • 5
  • I think the only problem here is each iteration gets executed at the same time, the var time needs to be incremented at each iteration. If I replace the "500" in your code with "time" and add an increment, I get a whole bunch of errors. – Pim Dec 13 '16 at 22:01
  • I proposed a improved that random a number between 500 and 599. – edulego Dec 14 '16 at 16:21
1
function asyncForEach(arr, cb) {
    return arr.reduce((p,c)=>{
        return p.then(()=>cb(c));
    }, Promise.resolve());
}
function wait(ms) {
    return ()=>new Promise(resolve=>setTimeout(resolve, ms));
}

const DELAY = 500; //ms
function iterateAddresses() {
    return asyncForEach(addresses_google, address => 
      getDistanceMatrix(address)
        .then(processResult)
        .then(wait(DELAY)));
}

iterateAddresses();

getDistanceMatrix is a promisified version of the function you supplied to $.each.

processResult is a promisified version of callback.

Ben Aston
  • 53,718
  • 65
  • 205
  • 331
  • How do I promisify these? :-) Never heard about JS promises up until today, I'm reading up on them. – Pim Dec 13 '16 at 23:55