Add a delay after each iteration with the forEach loop

Is there an easy way to slow down iteration in forEach (with simple javascript)? For instance:

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

items.forEach(function(el) {
  // do stuff with el and pause before the next el;
});
+4
source share
6 answers

What you want to achieve is entirely possible with help Array#forEach- although you could think of it differently. You may not do the following:

var array = ['some', 'array', 'containing', 'words'];
array.forEach(function (el) {
  console.log(el);
  wait(1000); // wait 1000 milliseconds
});
console.log('Loop finished.');

... and get the result:

some
array          // one second later
containing     // two seconds later
words          // three seconds later
Loop finished. // four seconds later

JavaScript does not have a synchronous function waitor sleepthat blocks all code after it.

- JavaScript - . setTimeout . , Array#forEach: :

var array = ['some', 'array', 'containing', 'words'];
var interval = 1000; // how much time should the delay between two iterations be (in milliseconds)?
array.forEach(function (el, index) {
  setTimeout(function () {
    console.log(el);
  }, index * interval);
});
console.log('Loop finished.');
Hide result

index, , . : console.log('Loop finished.') . , setTimout .

JavaScript - , . forEach.

, Promise s. :

var array = ['some', 'array', 'containing', 'words'];
var interval = 1000; // how much time should the delay between two iterations be (in milliseconds)?
var promise = Promise.resolve();
array.forEach(function (el) {
  promise = promise.then(function () {
    console.log(el);
    return new Promise(function (resolve) {
      setTimeout(resolve, interval);
    });
  });
});

promise.then(function () {
  console.log('Loop finished.');
});
Hide result

Promise forEach/map/filter .


, . , Array#forEach. :

var array = ['some', 'array', 'containing', 'words'];
var interval = 2000; // how much time should the delay between two iterations be (in milliseconds)?

var loop = function () {
  return new Promise(function (outerResolve) {
    var promise = Promise.resolve();
    var i = 0;
    var next = function () {
      var el = array[i];
      // your code here
      console.log(el);
      if (++i < array.length) {
        promise = promise.then(function () {
          return new Promise(function (resolve) {
            setTimeout(function () {
              resolve();
              next();
            }, interval);
          });
        });
      } else {
        setTimeout(outerResolve, interval);
        // or just call outerResolve() if you don't want to wait after the last element
      }
    };
    next();
  });
};

loop().then(function () {
  console.log('Loop finished.');
});

var input = document.querySelector('input');
document.querySelector('button').addEventListener('click', function () {
  // add the new item to the array
  array.push(input.value);
  input.value = '';
});
<input type="text">
<button>Add to array</button>
Hide result
+5

setTimeout

:

var items = ['a', 'b', 'c']
var i = 0;
(function loopIt(i) {
  setTimeout(function(){
      // your code handling here
      console.log(items[i]);
      if(i < items.length - 1)  loopIt(i+1)
    }, 2000);
})(i)
Hide result
+1

, :

var items = document.querySelectorAll('.item'), i;

for (i = 0; i < items.length; ++i) {
  // items[i] <--- your element
}

JavaScript forEach, , querySelectorAll

,

0

You can use cycles async/await, Promise, setTimeout()and for..ofto perform tasks in a sequence, where durationyou can set before running the task

(async() => {

  const items = [{
    prop: "a",
    delay: Math.floor(Math.random() * 1001)
  }, {
    prop: "b",
    delay: 2500
  }, {
    prop: "c",
    delay: 1200
  }];

  const fx = ({prop, delay}) =>
    new Promise(resolve => setTimeout(resolve, delay, prop)) // delay
    .then(data => console.log(data)) // do stuff

  for (let {prop, delay} of items) {
    // do stuff with el and pause before the next el;
    let curr = await fx({prop, delay});
  };
})();
Run codeHide result
0
source

I think recursion offers the simplest solution.

function slowIterate(arr) {
  if (arr.length === 0) {
    return;
  }
  console.log(arr[0]); // <-- replace with your custom code 
  setTimeout(() => {
    slowIterate(arr.slice(1));
  }, 1000); // <-- replace with your desired delay (in milliseconds) 
}

slowIterate(Array.from(document.querySelector('.item')));
0
source

Generators

function* elGenLoop (els) {
  let count = 0;

  while (count < els.length) {
    yield els[count++];
  }
}

// This will also work with a NodeList
// Such as `const elList = elGenLoop(document.querySelector('.item'));`
const elList = elGenLoop(['one', 'two', 'three']);

console.log(elList.next().value); // one
console.log(elList.next().value); // two
console.log(elList.next().value); // three

This gives you full control over when you want to access the next iteration in the list.

0
source

Source: https://habr.com/ru/post/1682986/


All Articles