简体   繁体   中英

JavaScript block loop logic

My code has an array with numerous objects, these objects which are URL'S, with them I make a loop that runs through this array and makes a request for each url in the array. But I need my loop to go through the array in blocks, Ex: every 10; until you reach the end, all this so that you don't do it instantly and end up overloading the server and also so that it doesn't take too long to go from 1 in 1 because the array is very large, the code base is basically that.

const array = ["URL-1","URL-2","URL-3"] etc...

for (var i = 0; i < array.length; i++) {
    axios.get(array[i], (res) => {
        const res = res;
    });
}

There most be a better way but by using the setTimeOut option you could try

let index = 0;
const maxIterations = 10;

function checkUrls() {

        for (var i = index; i < index + maxIterations; i++) {
            axios.get(array[i], (res) => {
            const res = res;
        }
        index += maxIterations;
        if (index >= array.length - maxIterations) {
            endOfArray = true;
            clearInterval(timer);
        }

}

const timer = setInterval(checkUrls, 10000);

Or something along those lines, hope that helps

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