如何为setInterval创建动态变量?
我使用节点和 ejs 创建一个 hmtl 页面,其中包含不可预见的元素数量。我想为一些、没有或全部这些元素创建一个 setInterval,具体取决于用户正在做什么。
问题是,我无法为 setInterval 创建动态变量,以便稍后可以取消这些间隔。
也许我只需要另一种更简单的方法,但目前我被困在这里。
camContainer.forEach(element => {
clearInterval(intervalVar);
if (!element.classList.contains("hidden")) {
countVisible++;
intervalVar = setInterval(showConsole, 1500);
} else {
countHidden ++;
}
count++;
})
我用数组而不是常规变量尝试过,但这也不起作用
intervalVar[count] = setInterval(showConsole, 1500);
I create a hmtl page with node and ejs with an unforseeable number of elements. I would like to create a setInterval for some, none or all of those elements, depending what the user is doing.
The problem is, that I am not able to create a dynamically variable for the setInterval so that I can later on cancel those Intervals.
Maybe I just need another simpler approach but at the moment I am stuck here.
camContainer.forEach(element => {
clearInterval(intervalVar);
if (!element.classList.contains("hidden")) {
countVisible++;
intervalVar = setInterval(showConsole, 1500);
} else {
countHidden ++;
}
count++;
})
I tried it with an Array instead of a regular variable but that didnt work either
intervalVar[count] = setInterval(showConsole, 1500);
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
您在数组上的方向是正确的,但您需要将项目推入其中:
当您想要取消间隔时,请使用
slice
或pop
将其从数组中删除>,具体取决于您选择要取消的项目的方式。You're on the right track with an array, but you need to push items onto it:
When you want to cancel an interval, remove it from the array with
slice
orpop
, depending on how you're selecting the item to cancel.