What you want to achieve is totally possible with Array#forEach
— although in a different way you might think of it. You can not do a thing like this:
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 output:
some
array // one second later
containing // two seconds later
words // three seconds later
Loop finished. // four seconds later
There is no synchronous wait
or sleep
function in JavaScript that blocks all code after it.
The only way to delay something in JavaScript is in a non–blocking way. That means using setTimeout
or one of its relatives. We can use the second parameter of the function that we pass to Array#forEach
: it contains the index of the current element:
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.');
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…