简体   繁体   中英

How to iterate through javascirpt array with a sleep/delay?

I am trying to set view & marker at one geo location and after a delay/sleep set the marker in another location. I'm using leaflet.js. There is a data array

[
    {
        "city": "City_1",
        "lat": 8.702127234287211,
        "lon": 77.1684975438538,
        "temp": 25,
        "icon": "🥑"
    },
    {
        "city": "City_2",
        "lat": 9.083099761723636, 
        "lon": 74.81806072890778, 
        "temp": 0,
        "icon": "🥦"
    }
]

and on button click the data is read and looped. Tried setInterval() with no success.

const startUpdating = async () => {    
    const response = await fetch('data.json');
    const data = await response.json();
    const marker = L.marker();// init marker

    for (i of data) {
        // Tried setInterval(setView, 1000); // no success.
        await map.setView([i.lat, i.lon], 10);
        marker.setLatLng([i.lat, i.lon]).addTo(map);
    }
}
startBtn.addEventListener('click', startUpdating);

So how to set a delay so that data is read from array, set the marker and view on map, wait for some time and then again iterate.

Fortunately, you are already in an async context. setTimeout is easy to promisify:

function delay(time) {
  return new Promise(resolve => setTimeout(resolve, time));
}

Then simply insert await delay(1000) to wait for one second.

Instead of looping it with a for loop, you can drain your data array using a recursive function call with a setTimeout which should pretty much look like this.

const response = await fetch('data.json');
const data = await response.json();
// ... some other codes
const setNext = () => {
  if (data.length) {
    const item = data.shift();
    // ... set you marker here    
  }

  if (data.length) {
    setTimeout(setNext, 1000);
  }
};
setNext();

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM