2

My project call the Google Map API which have speed limitation. So my for loop have to be slowed down.

I have the following for loop JS code:

// Iterate Data and create markers
for (var i in Data) {
    address = Data[i].address;
    tag = Data[i].tag
    placeAddressOnMap(address, tag);
    i = i + 1 ;
}

How should I process to slow down an existing for loop ?


I tried the following JS code which doesn't work:

// Iterate Data and create markers
for (var i in Data) {
    address = Data[i].address;
    tag = Data[i].tag
    placeAddressOnMap(address, tag);
    i = i + 1 ;
    setTimeout(function () { i = i }, 2000); // failing delay using setTimeout(function () { }, 2000);
}
Hugolpz
  • 17,296
  • 26
  • 100
  • 187
  • 1
    Seems like your question has been answered before: [http://stackoverflow.com/questions/3583724/how-do-i-add-a-delay-in-a-javascript-loop] – Hasan Mar 25 '13 at 16:12
  • 1
    The delay is not failing. `setTimeout(function () { i = i }, 2000);` executes `i = i` after a delay of 2 seconds, while the `for` loop continues it's execution. – ShuklaSannidhya Mar 25 '13 at 16:12
  • But that doesn't slow down the iteration of my Data. Edit: Oh, Hasan Ayan's link is my answer and explanation. – Hugolpz Mar 25 '13 at 16:17

1 Answers1

5

I believe you want to set an interval, I don't have your full code, but something among the lines of this:

var timesRun = -1;
var interval = setInterval(function(){
    timesRun += 1;
    if(timesRun == Data.length){
        clearInterval(interval);
    }
    address = Data[i].address;
    tag = Data[i].tag
    placeAddressOnMap(address, tag);
}, 2000); 

Little demo where it counts: Demo

The reason why your code doesn't work, is because the for loop keeps on going. Because setTimeout is asynchronous. Let's say an iteration of your for loop takes 1 milisecond (just an example). The code in your setTimeout will be fired at 0, 2001, 2002, 2003, 2004 miliseconds etc.. not 0, 2000, 4000, etc.

Peter Rasmussen
  • 16,474
  • 7
  • 46
  • 63