I\'m confused with using setTimeout and the each iterator. How can I rewrite the following so that the console outputs each name after a delay of 5 seconds? Currently the
array.forEach accepts a callback function which means it already creates a new function scope and as the nature of setTimeout is non-blocking which return immediately you just need to increment delay for callback function execution with every iteration:
var ary = ['kevin', 'mike', 'sally'];
ary.forEach(function(person, index){
setTimeout(function(){
console.log(person);
}, 5000 * (index + 1));
})
In case if you want to achieve the same with for loop you can make use of IIFE or let keyword
IIFE example:
var ary = ['kevin', 'mike', 'sally'];
for(var i = 1; i <= ary.length; i++){
(function(i){
setTimeout(function(){
console.log(ary[i - 1]);
}, 5000 * i);
})(i)
}
let keyword example: [ECMAScript 6]
var ary = ['kevin', 'mike', 'sally'];
for(let i = 1; i <= ary.length; i++){
setTimeout(function(){
console.log(ary[i - 1]);
}, 5000 * i);
}