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);
});
console.log('Loop finished.');
... and get the result:
some
array
containing
words
Loop finished.
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;
array.forEach(function (el, index) {
setTimeout(function () {
console.log(el);
}, index * interval);
});
console.log('Loop finished.');
Hide resultindex, , . : console.log('Loop finished.') . , setTimout .
JavaScript - , . forEach.
, Promise s. :
var array = ['some', 'array', 'containing', 'words'];
var interval = 1000;
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 resultPromise forEach/map/filter .
, . , Array#forEach. :
var array = ['some', 'array', 'containing', 'words'];
var interval = 2000;
var loop = function () {
return new Promise(function (outerResolve) {
var promise = Promise.resolve();
var i = 0;
var next = function () {
var el = array[i];
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);
}
};
next();
});
};
loop().then(function () {
console.log('Loop finished.');
});
var input = document.querySelector('input');
document.querySelector('button').addEventListener('click', function () {
array.push(input.value);
input.value = '';
});
<input type="text">
<button>Add to array</button>
Hide result