larry chambers
larry chambers

Reputation: 503

Adding a timeout to a for loop

I am trying to add a timeout delay to a for loop. It currently loops through locations in a variable and places a marker for all in it. It works fine but I would like it to show them with a slight time delay. I am trying to use setTimeOut function but when I add it, it cant load the data?

The loop working before I add the timeout is

 for (var i = 0; i < data.length; i++) {
        if (data[i].lat != null) {
        markers[data[i].username]= new L.marker([data[i].lat, data[i].lng], { bounceOnAdd: true,draggable: true, icon: redIcon });
        map.addLayer(markers[data[i].username]);
        markers[data[i].username].bindPopup('Online :' + data[i].username);
      }

And what doesnt work with the timeout added.

 for (var i = 0; i < data.length; i++) { setTimeout(function () {
        if (data[i].lat != null) {
        markers[data[i].username]= new L.marker([data[i].lat, data[i].lng], { bounceOnAdd: true,draggable: true, icon: redIcon });
        map.addLayer(markers[data[i].username]);
        markers[data[i].username].bindPopup('Online :' + data[i].username);
      }, 3000); 
      } 

Upvotes: 1

Views: 210

Answers (2)

Andy
Andy

Reputation: 63524

Instead of using a loop, use a function with a setTimeout. It plots a marker using the data in the first element then calls the function again with the rest of the array.

const data = [0, 1, 2, 3, 4, 5];

function plotMarker(data) {
  const [head, ...rest] = data;
  if (data.length) {

    // plot your marker
    console.log(head);
    setTimeout(() => plotMarker(rest), 1000);
  }
}

plotMarker(data);

Upvotes: 3

Dacre Denny
Dacre Denny

Reputation: 30360

Perhaps you could wrap your marker creation logic in an async method, as shown below?

By doing this, you could continue to use the for-loop construct as you currently are, and then introduce a delay between creation of markers via:

await new Promise(resolve => setTimeout(resolve, 3000))

Using this pattern, your code would then look something like this:

async function processData(data) {

  for(var i = 0; i < data.length; i++) {
  
    console.log(`waiting 3000 ms`);

    // Delay creation of marker for data[i] by 3 seconds
    await new Promise(resolve => setTimeout(resolve, 3000));

    // Create new marker from data[i]
    const marker = data[i];

    console.log(`create new marker from item: ${ marker }`);

    /*
    markers[data[i].username]= new L.marker([
        data[i].lat, data[i].lng
    ], { 
        bounceOnAdd: true,
        draggable: true, 
        icon: redIcon 
    });

    map.addLayer(markers[data[i].username]);
    markers[data[i].username].bindPopup('Online :' + data[i].username);
    */
  }
}

processData([1,2,3,4])

Upvotes: 0

Related Questions