Add a delay after executing each iteration with forEach loop

Viewed 53440

Is there an easy way to slow down the iteration in a forEach (with plain javascript)? For example:

var items = document.querySelector('.item');

items.forEach(function(el) {
  // do stuff with el and pause before the next el;
});
8 Answers

With JS Promises and asnyc/await syntax, you can make a sleep function that really works. However, forEach calls each iteration synchronously, so you get a 1 second delay and then all of the items at once.

const items = ["abc", "def", "ghi", "jkl"];

const sleep = (ms) => new Promise((res) => setTimeout(res, ms));

items.forEach(async (item) => {
  await sleep(1000);
  console.log(item);
});

What we can do instead is use setInterval and clearInterval (or setTimeout but we're using the former) to make a timed forEach loop like so:

function forEachWithDelay(array, callback, delay) {
  let i = 0;
  let interval = setInterval(() => {
    callback(array[i], i, array);
    if (++i === array.length) clearInterval(interval);
  }, delay);
}

const items = ["abc", "def", "ghi", "jkl"];

forEachWithDelay(items, (item, i) => console.log(`#${i}: ${item}`), 1000);

You can make a promise and use it with a for, the example has to be in an async / await function:

    let myPromise = () => new Promise((resolve, reject) => {
      setTimeout(function(){
        resolve('Count')
      }, 1000)
    })
  
    for (let index = 0; index < 100; index++) {
      let count = await myPromise()
      console.log(`${count}: ${index}`)    
    }
Related