SetTimeOut does not work

0

I'm using a Google API, and I need it to wait for at least 3 seconds before making another request, I tried to do this but I could not, setTimeOut does not wait for 3 seconds!

function getLatLong(polos, res) {
  polos.forEach(element => {
    setTimeout(() => {
      request({
        url: 'https://maps.googleapis.com/maps/api/geocode/json?address=' + element.endereco + ' - ' + element.cep + ' - BRASIL' + '&key=AIzaSyCh2Y3mfj2uJtXBHoYeAWvwyHvYCN0iKlk',
        json: true
      }, function (error, response, data) {

        if (data["results"][0]) {
          console.log(data["results"][0].geometry["location"]);
        }else {
          console.log("Não pegou", element.nome)
          return false;
        }
        // res.send(data);
        // var latLong = (data["results"][0].geometry["location"]);
        // console.log(latLong);
      });
    }, 3000);
  });
}

Console output:

{ lat: -29.6871895, lng: -53.8090582 }
{ lat: -23.4391891, lng: -51.9142814 }
{ lat: -23.1814106, lng: -50.6480145 }
Não pegou ASTORGA - PR
Não pegou POÇOS DE CALDAS - MG
Não pegou SALVADOR - BA
Não pegou GOIOERÊ - PR
{ lat: -20.4557007, lng: -54.5936527 }
{ lat: -26.9205582, lng: -49.0696077 }
Não pegou CAMPO MOURÃO - PR
{ lat: -27.5991936, lng: -48.6084431 }
Não pegou PATROCÍNIO - MG
Não pegou SUZANO - SP
Não pegou PORECATU - PR
{ lat: -22.5292946, lng: -52.1804526 }
{ lat: -10.1870213, lng: -48.3282553 }
Não pegou LAGES - SC
{ lat: -26.488296, lng: -49.0828988 }
{ lat: -16.4696391, lng: -54.6311907 }
{ lat: -23.3034209, lng: -51.1419351 }
Não pegou OLINDA - PE
{ lat: -24.9553923, lng: -53.4575696 }
{ lat: -19.9689819, lng: -44.2008435 }
Não pegou RIO DE JANEIRO - TIJUCA - RJ

The problem is he is not waiting 3 seconds before making another request. What could I do?

    
asked by anonymous 26.03.2018 / 19:38

1 answer

1

They wait for the 3 seconds however, all timeouts will be released after 3 seconds, at the same time . You should use a counter, so the second timeout will exit after 6 seconds.

  var cont = 1;
  polos.forEach(function(element){
     setTimeout(function(){
       ...
     }, 3000*cont);
     cont++;
  });

The problem would already be solved with 2 lines of code, with this:

  • The first timeout will be released in 3 seconds;
  • The second timeout will be released in 6 seconds;
  • The third, 9 seconds;

and so on.

    
26.03.2018 / 19:55