[英]Fadeout multiple elements with timeout only fades last one in list
I'm trying to fadeout message containers after a few seconds.我试图在几秒钟后淡出消息容器。 Usually there's only one, and that works fine, but when there are 2 or more, only the last one seems to get processed.通常只有一个,而且效果很好,但是当有 2 个或更多时,似乎只有最后一个被处理。
Code:代码:
function fadeOut(elementToFade) {
var element = document.getElementById(elementToFade);
console.log(`fo element = ${element}, ${element.id}`)
element.style.opacity = (parseFloat(element.style.opacity) - 0.1).toString();
if (parseFloat(element.style.opacity) <= 0.0) {
element.style.display = "none";
} else {
setTimeout("fadeOut(\"" + elementToFade + "\")", 150);
// setTimeout("fadeOut(\"" + element.id + "\")", 150);
}
};
var message_elements_nodelist = document.querySelectorAll("div[id^='message_container']");
var pauseBeforeFadeout = 5000;
for (var i = 0; i < message_elements_nodelist.length; i++) {
var el = document.getElementById(message_elements_nodelist[i].id)
console.log(`element = ${el}, ${el.id}`)
setTimeout(function () {
el.style.opacity = "1.0";
fadeOut(el.id);
}, pauseBeforeFadeout);
};
The console logging shows:控制台日志显示:
element = [object HTMLDivElement], message_container-0
element = [object HTMLDivElement], message_container-1
2fo element = [object HTMLDivElement], message_container-1
10fo element = [object HTMLDivElement], message_container-1
So the code finds both elements, but then the timeout only seems to get applied to the last one in the list and I cannot work out why this would be.所以代码找到了这两个元素,但是超时似乎只应用于列表中的最后一个元素,我无法弄清楚为什么会这样。
Edit编辑
Putting in a Promise
now looks like this:放入Promise
现在看起来像这样:
const message_elements_nodelist = document.querySelectorAll("div[id^='message_container']")
const pauseBeforeFadeout = 5000
async function fadeOut(elementToFade) {
const element = document.getElementById(elementToFade);
console.log(`fo element = ${element}, ${element.id}`)
element.style.opacity = (parseFloat(element.style.opacity) - 0.1).toString()
if (parseFloat(element.style.opacity) <= 0.0) {
element.style.display = "none"
} else {
setTimeout("fadeOut(\"" + elementToFade + "\")", 150)
}
}
async function fadeOutAllMessages() {
for (let i = 0; i < message_elements_nodelist.length; i++) {
const el = document.getElementById(message_elements_nodelist[i].id)
console.log(`element = ${el}, ${el.id}`)
await new Promise(resolve => setTimeout(() => {
el.style.opacity = "1.0"
fadeOut(el.id)
}, pauseBeforeFadeout))
}
}
fadeOutAllMessages()
Unfortunately, now the first message is cleared, but the second isn't, and the console.log
messages look like this:不幸的是,现在第一条消息被清除了,但第二条没有, console.log
消息如下所示:
element = [object HTMLDivElement], message_container-0
fo element = [object HTMLDivElement], message_container-0
9 fo element = [object HTMLDivElement], message_container-0
Those last 9 messsages appear 5 seconds after the first, so one await
is working, then it seems to bundle them all through with only the 1st loop instance.最后 9 条消息在第一条消息后 5 秒出现,所以一个await
正在工作,然后它似乎只将它们与第一个循环实例捆绑在一起。
This is happening because of asynchronous method (setTimeout in this case) is used inside for loop.这是因为在 for 循环中使用了异步方法(在这种情况下为 setTimeout)。 Before the asynchronous method execution, variable i
is already incremented (the loop does not wait for the asynchronous code inside), hence setTimeout will be executed multiple times and variable i
is always at it's last value for all the callbacks.在异步方法执行之前,变量i
已经递增(循环不会等待内部的异步代码),因此 setTimeout 将被执行多次,并且变量i
始终是所有回调的最后一个值。
Consider using async/await
inside the loop.考虑在循环内使用async/await
。
async function yourFunction() {
for (let i = 0; i < 10; i++) {
// wait for the promise before incrementing i and advancing the loop
await new Promise(resolve => resolve(setTimeout(() => console.log(i),
1000)))
}
}
The other solution is calling a function which is created outside of the loop.另一种解决方案是调用在循环外创建的 function。
const setDelay = (i) => {
setTimeout(() => {
console.log(i);
}, 1000);
}
for (let i = 0; i < 5; i++) {
setDelay(i);
}
You can find more examples in this topic: Asynchronous Process inside a javascript for loop您可以在本主题中找到更多示例: Asynchronous Process inside a javascript for loop
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.