[英]How to add a delay in a JavaScript loop before the next iteration?
[Solved thanks to the best answer here] [解决了这里的最佳答案]
The page is now finished and works smoothly. 该页面现已完成并且可以正常工作。 Take a look at the result on codepen: 看一下代码笔上的结果:
https://codepen.io/Lietsaki/pen/pXOeKO https://codepen.io/Lietsaki/pen/pXOeKO
I'm making a simple website that contains some information about the Doge meme. 我正在制作一个简单的网站,其中包含有关Doge meme的一些信息。 I want some phrases to pop up in every section, so I added a class with "display: none" and set up some events in JS to remove the classes as the user clicks on the next section. 我希望在每个部分中弹出一些短语,因此我添加了一个带有“ display:none”的类,并在JS中设置了一些事件以在用户单击下一部分时删除这些类。
However, so far I've only been able to remove all classes at once instead of one class being removed every n seconds. 但是,到目前为止,我只能一次删除所有类,而不是每n秒删除一个类。
I've tried using a for loop with setInterval, but it didn't work. 我已经尝试过使用带有setInterval的for循环,但是没有用。 So I tried making a function that loops until a condition is met with setTimeout, but that removes all classes at once and throws a console error: 因此,我尝试制作一个循环直到setTimeout满足条件的函数,但该函数立即删除所有类并引发控制台错误:
"Uncaught TypeError: Cannot read property 'classList' of undefined at addPhrase (whoisdoge.js:78) at whoisdoge.js:83" “未捕获的TypeError:无法在whoisdoge.js:83的addPhrase(whoisdoge.js:78)读取未定义的属性'classList'”
Please check the code below. 请检查下面的代码。
// Select the phrases with the class ".phrase1"
var phrase1 = document.querySelectorAll(".phrase1");
// Turn it into an array and get its length(30) into a variable
var phrase1Arr = Array.from(phrase1);
// Function to remove a class every 3 seconds (NOT WORKING)
function addPhrase(l){
phrase1Arr[l].classList.remove("disappear");
if (l < 30){
setTimeout(function(){
l++;
addPhrase(l)
}, 3000);
}
}
Your function is breaking because you're trying to remove index 30 when there are only 30 elements in your array. 您的函数中断了,因为当数组中只有30个元素时,您试图删除索引30。 (So you're trying to remove the 31st element) (因此,您尝试删除第31个元素)
You should move your remove into the same if statement that you already have. 您应该将remove移至已经拥有的if语句中。
function addPhrase(l){
if (l < 30){
phrase1Arr[l].classList.remove("disappear");
setTimeout(function(){
l++;
addPhrase(l)
}, 3000);
}
}
You're also calling a function instead of referencing a function in your addEventListener
calls: 您还正在调用函数,而不是在addEventListener
调用中引用函数:
sec0[0].addEventListener("click", addPhrase(0));
Should be 应该
sec0[0].addEventListener("click", function(){
addPhrase(0)
});
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.