How to pause a FOR loop in Javascript in a functio

2019-07-13 03:54发布

问题:

There's a query per second limit in Google Places API, so I need to slow down my loop which sends requests:

function callback(results, status) {
  if (status != google.maps.places.PlacesServiceStatus.OK) {
    alert(status);
    return;
  }
      for (var i = 0, result; result = results[i]; i++) {
    RequestInfo(result);
  }
}

Any idea how I can do that? I'm a bit of a newb.

回答1:

Recursive solution,

function requestInfoWrapper(results, i) {
    i = i + 1;
    if (i >= results.length) {return};
    requestInfo(results[i]);
    setTimeout(function() {requestInfoWrapper(results, i);}, 1000);
}

Some example code to test it,

   var results = ["test 1", "test 2", "test 3"];
   function requestInfo(str) {console.log(str);}
   requestInfoWrapper(results, -1);

Also integrated with your code would just be,

function callback(results, status) {
    if (status != google.maps.places.PlacesServiceStatus.OK) {
        alert(status);
        return;
    }

    requestInfoWrapper(results, -1);
}


回答2:

for (var i = 0, result; result = results[i]; i++){
    (function(result){
        setTimeout(function(){
            RequestInfo(result);
        }, 1e3 * i);
    })(result);
}

You can use setTimeout and space them out to execute every 1 second * n (where n is the current iteration number).

And, for the more to the point answer, JavaScript doesn't have a "sleep" method (nor would you want it to; it's single threaded and would tie up anything else while it waited).



回答3:

You can use setTimeout to call the function recursively.

var i = 0;
function callback(results, status) {
  if (status != google.maps.places.PlacesServiceStatus.OK) {
    alert(status);
    return;
  }
  setTimeout(function() { 
    i++; 
    if (i < results.length) { 
      RequestInfo(results[i]);
      callback(results, status);
    }
  }, 1000);
}