Hugolpz
Hugolpz

Reputation: 18258

JS: how to delay or set an Interval in a for-loop?

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);
}

Upvotes: 2

Views: 375

Answers (1)

Peter Rasmussen
Peter Rasmussen

Reputation: 16922

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.

Upvotes: 5

Related Questions