【问题标题】:setTimeout inside ForEach does not wait with the specific ms givenForEach 中的 setTimeout 不会等待给定的特定毫秒
【发布时间】:2020-08-24 14:43:55
【问题描述】:

ForEach console.log 的速度非常快。但我需要它每 8 秒等待一次 console.log 设置中的下一个项目。我尝试了 setTimeout,但它似乎没有在给定的特定 ms 处显示 console.log。

const completedIds = [];

//Dom mutation observer
const observeChat = new MutationObserver(function(mutationsList) {
  for (let mutation of mutationsList) {
    if (mutation.addedNodes.length) {


      for (i = 0; i < mutation.addedNodes.length; i++) {
mutation.addedNodes[i].firstChild.naturalWidth < 51 ? pm(mutation.addedNodes[i].firstChild.src.slice(-48, -12)) : false
      }
      
    }
  }
});
observeChat.observe(document.querySelector('.accounts-container__list'), {attributes: true, childList: true, subtree: false});

// Pm function
pm = ids => {
  observeChat.disconnect();
  if (!completedIds.includes(ids)) {
    const img = new Set().add(ids).forEach(function(id, index) {
      setTimeout(function() { // Not working. Does NOT print in console every 8sec
        console.log(id)
      }, index * 8000)
    })
  }
  observeChat.observe(document.querySelector('.accounts-container__list'), {attributes: true, childList: true, subtree: false});
}

【问题讨论】:

  • 您没有将其设置为记录每 8秒,而是在 8秒之后记录。
  • 我的意思是。我需要它每 8 秒等待一次,然后才能移动到集合中的下一个项目。
  • 实际发生了什么?超时/间隔也不准确。

标签: javascript loops time foreach delay


【解决方案1】:

这里有几个问题。

  1. 您正在创建一个Set,其中只有一个条目。 add 不会分散您提供的条目。如果你给它一个数组,你会得到一个只有那个数组的集合。我怀疑你想把它传播出去。

  2. 集合的“索引”与其值相同,因此index * 8000 将尝试将您刚刚添加的 ID 乘以 8000。它不像一个数组的 forEach 给您的索引。

  3. img 将永远是undefined,因为Set.prototype.forEach 的返回值是undefined。

我怀疑您正在使用 Set 来获取唯一值。如果是这样,您希望:

  1. 使用new Set(...ids) 创建集合,然后

  2. 在使用forEach之前将其转换回数组

  3. 以其他方式初始化img。我不清楚它是什么意思,所以我无能为力...

类似的东西:

    [...new Set(ids)].forEach(function(id, index) {
//  ^^^^−−−−−−−^^^^^^−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−− here
        setTimeout(function() {
            console.log(id);
        }, index * 8000);
    });

现场示例:

const ids = ["a", "b", "c"];
[...new Set(ids)].forEach(function(id, index) {
    setTimeout(function() {
        console.log(id, new Date());
    }, index * 8000);
});

或者,您可以使用带有计数器的 for-of 循环:

let index = 0;
for (const id of [...new Set(ids)]) {
    setTimeout(function() {
        console.log(id);
    }, index++ * 8000);
}

现场示例:

let index = 0;
for (const id of [...new Set(ids)]) {
    setTimeout(function() {
        console.log(id);
    }, index++ * 8000);
}

【讨论】:

    猜你喜欢
    • 2011-07-03
    • 1970-01-01
    • 2013-07-13
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-04-06
    • 1970-01-01
    相关资源
    最近更新 更多