You can do this in three different ways
1. with IIFE
------------
let fruits = ["banana", "apple", "Orange"];
for (let index = 0; index < fruits.length; index++) {
(function(fruits, index) {
setTimeout(() => {
console.log(fruits[index]);
}, index * 1000);
})(fruits, index);
}
2. with Closure, as it reference the outer scope variable even after
the main function execution
----------------------------------
let fruits = ["banana", "apple", "Orange"];
function closerWithsettimeout() {
return function() {
fruits.forEach(function(elem, i) {
setTimeout(() => {
console.log(elem);
}, 1000 * i);
});
};
}
closerWithsettimeout()();
3. With promise
----------------
let fruits = ["banana", "apple", "Orange"];
fruits.forEach((elem, i) => {
var p = new Promise((resolve, reject) => {
fruits[0] === "banana" ?
setTimeout(() => {
resolve(elem);
}, i * 1000) :
reject(new Error("Fruits cannot be bought"));
});
p.then(result => console.log(result)).catch(err => console.log(err.message));
});