add delay between function calls inside a loop

The easiest way is to use async/await:

function sleep(ms) {
    return new Promise((res, rej) => {
        setTimeout(() => {
            res();
        }, ms);
    });
}

async function main() {
    const arr = [1, 2, 3];
    for (const a of arr) {
        console.log(a);
        await sleep(1000);
    }
}

main();

CLICK HERE to find out more related problems solutions.

Leave a Comment

Your email address will not be published.

Scroll to Top