javascript

Array iteration with setTimeout() javascript

The code will iterate through javascript array items and console each item with one-second delay.

const persons = ['John', 'Rick', ' Carol'];

let delay = 0;
persons.forEach(function (person) {
    setTimeout(function () {
        console.log(person);
    }, 1000 + delay);
    delay += 1000;
});

We have an array of persons that contains person names and we are iterating those using Array.forEach() method. Inside this method, we are using setTimeout() method that will show each item in the console with a one-second delay of each iteration.

Live Demo

You can check the live demo of the above code here.

Was this helpful?