【问题标题】:Changing the value of Timeout depending on the array value根据数组值更改 Timeout 的值
【发布时间】:2021-12-10 05:53:19
【问题描述】:

我想每 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)
}

【问题讨论】:

  • 欢迎来到 Stack Overflow!请拿起tour(你会得到一个徽章!)并通读help center,尤其是How do I ask a good question?你最好的选择是做你的研究,search关于SO和其他地方的相关主题,并给它去吧。 如果您在进行更多研究和搜索后遇到困难并且无法摆脱困境,请发布minimal reproducible example 展示您的尝试并具体说明您遇到的问题。人们会很乐意提供帮助。
  • 旁注:i++;setTimeout 回调中没有做任何有用的事情,它增加了一个永远不会被任何其他代码使用的变量。 (当你在 for 声明中使用 let 时,每个循环迭代都会得到它的 自己的 i 变量——你想要在上面,那部分是正确的,只需删除不必要的 @987654333 @.)

标签: javascript timeout settimeout


【解决方案1】:

使用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`);
    }
  });

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2021-12-21
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-10-10
    • 1970-01-01
    • 2013-03-04
    • 2020-12-26
    相关资源
    最近更新 更多