Settimeout does not work

Asked

Viewed 524 times

-1

I’m using a Google API, and I need for the request part to wait for at least 3 seconds before making another request, I tried to do this, but could not, setTimeOut does not wait 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’s not waiting 3 seconds before making another request. What could I do?

2 answers

1

These 3 seconds were specified by Google or you just don’t want two requests to be made at the same time?

You could change your code so that the function treats only one element, and when you finish processing the return, it calls itself to process the next element, as long as there is.

// A primeira chamada é só para o primeiro elemento
getLatLong(polos, 0, res);

function getLatLong(polos, index, res) 
{ 
    request({ 
        url: 'https://maps.googleapis.com/maps/api/geocode/json?address=' + polos[index].endereco + ' - ' + polos[index].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); 

            // Chama o próximo elemento
            if (index < polos.lenght - 1)
                getLatLong(polos, index + 1, res);
        }); 
    }

1

They wait the 3 seconds however, all timeouts will be released after 3 seconds, at the same time. You must use a counter, so that the second timeout comes out after 6 seconds.

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

The problem would already be solved with 2 more 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.

  • It worked! , but is there no other way, I do it because the api does not let me make one request after another, there is some other way?

  • you can use Timer, but the code would be harder to understand. The best solution in my opinion is to call the next request, after the previous one is closed (recursively).

Browser other questions tagged

You are not signed in. Login or sign up in order to post.