如何解决ForEach中的setTimeout不等待给出的特定ms
ForEach console.log的运行速度非常快。但是我需要它每8秒等待一次,然后console.log记录Set中的下一项。我尝试了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'),subtree: false});
}
解决方法
这里有两个问题。
-
您正在创建一个
Set
,其中只有一个条目。add
不会分散您输入的内容。如果给它一个数组,那么您将得到一个仅包含该数组的集合。我怀疑您想散布它。 -
集合的“索引”与其值相同,因此
index * 8000
会尝试将您刚刚添加的ID乘以8000。它不像一个数组的{{1} }给您。 -
forEach
将始终为img
,因为Set.prototype.forEach
的返回值为undefined
。
我怀疑您正在使用undefined
来获取唯一值。如果是这样,您要:
-
使用
Set
创建集合,然后 -
在使用
之前将其转换回数组new Set(...ids)
-
以其他方式初始化
forEach
。我不清楚这是什么意思,所以我无法帮助那一部分...
遵循以下原则:
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);
}
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。