[英]How to add a delay in a JavaScript loop before the next iteration?
該頁面現已完成並且可以正常工作。 看一下代碼筆上的結果:
https://codepen.io/Lietsaki/pen/pXOeKO
我正在制作一個簡單的網站,其中包含有關Doge meme的一些信息。 我希望在每個部分中彈出一些短語,因此我添加了一個帶有“ display:none”的類,並在JS中設置了一些事件以在用戶單擊下一部分時刪除這些類。
但是,到目前為止,我只能一次刪除所有類,而不是每n秒刪除一個類。
我已經嘗試過使用帶有setInterval的for循環,但是沒有用。 因此,我嘗試制作一個循環直到setTimeout滿足條件的函數,但該函數立即刪除所有類並引發控制台錯誤:
“未捕獲的TypeError:無法在whoisdoge.js:83的addPhrase(whoisdoge.js:78)讀取未定義的屬性'classList'”
請檢查下面的代碼。
// 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);
}
}
您的函數中斷了,因為當數組中只有30個元素時,您試圖刪除索引30。 (因此,您嘗試刪除第31個元素)
您應該將remove移至已經擁有的if語句中。
function addPhrase(l){
if (l < 30){
phrase1Arr[l].classList.remove("disappear");
setTimeout(function(){
l++;
addPhrase(l)
}, 3000);
}
}
您還正在調用函數,而不是在addEventListener
調用中引用函數:
sec0[0].addEventListener("click", addPhrase(0));
應該
sec0[0].addEventListener("click", function(){
addPhrase(0)
});
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.