简体   繁体   English

如何使用睡眠/延迟遍历 javascirpt 数组?

[英]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.我正在使用 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.尝试setInterval()没有成功。

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.那么如何设置延迟以便从数组中读取数据,设置标记并在 map 上查看,等待一段时间然后再次迭代。

Fortunately, you are already in an async context.幸运的是,您已经处于async上下文中。 setTimeout is easy to promisify: setTimeout很容易承诺:

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

Then simply insert await delay(1000) to wait for one second.然后只需插入await delay(1000)等待一秒钟。

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.您可以使用带有 setTimeout 的递归 function 调用来耗尽您的数据数组,而不是使用 for 循环,它应该看起来像这样。

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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