我想每0.5秒从数组中打印一个字母,每2秒打印一个元音。
我成功地编写了一个代码,每0.5秒打印一次数组元素
var alphabet = ['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z']
var i = 0;
for (let i = 0; i < alphabet.length; i++){
setTimeout(function(){
console.log(alphabet[i]);
i++;
}, 500*i)
}
如何实现剩下的
if (alphabet[i] == 'a' | 'e' | 'i' | 'o' | 'u'){
setTimeout(function(){
console.log(alphabet[i]);
i++;
}, 2000*i)
}
使用Promise()
,您可以使用Promise.all ()
命令,其中Promise.all()
等待数组中的所有promise被处理。
function setIntervalForItem(input = [], vowels = ["a", "e", "i", "o", "u"], defaultInterval = [500, 2000])
{
const [interval, _interval] = defaultInterval;
var resultPromiseArray = new Array();
for (const char of input) {
const delay = vowels.indexOf(char) === -1 ? interval : _interval;
resultPromiseArray.push(new Promise(resolve => {
setTimeout(() => {
resolve({value: char, time: delay});
}, delay);
}));
}
return Promise.all(resultPromiseArray);
}
var alphabet = [
'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm',
'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z'
];
// Then just call:
setIntervalForItem(alphabet)
.then(result => {
for (const object of Object.entries(result)) {
const {value, time} = object[1];
console.log(`The delay for character [ ${value} ] was ${time} ms`);
}
});