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();
4
  • 1
    Possible duplicate of Applying delay between iterations of javascript for loop Commented Dec 13, 2016 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. Commented Dec 13, 2016 at 21:39
  • So add things to a collection, use a timeout and remove the items from the collection. Commented Dec 13, 2016 at 21:43
  • Variables from and to are unused? Commented Dec 13, 2016 at 22:37

2 Answers 2

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.

Sign up to request clarification or add additional context in comments.

1 Comment

How do I promisify these? :-) Never heard about JS promises up until today, I'm reading up on them.
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();

2 Comments

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.
I proposed a improved that random a number between 500 and 599.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.