簡體   English   中英

循環中的 clearInterval 不能按預期工作

[英]clearInterval in loop don't work as expected

我有問題當我刪除字母時,單詞仍然存在

我有兩個 h1 我從每個 h1 中刪除了單詞,當所有字母都被刪除時,我專門為每個 h1 停止間隔

圖像

 let mySelector = document.querySelectorAll(".writ-text"); for (let l = 0; l < mySelector.length; l++) { removeText = setInterval(function() { // Cut the last letter of the word and print the word after editing document.querySelectorAll(".writ-text")[l].textContent = document.querySelectorAll(".writ-text")[l].textContent.substr(0, document.querySelectorAll(".writ-text")[l].textContent.length - 1); // Check if the entire word has been deleted if (document.querySelectorAll(".writ-text")[l].textContent.length == 0) { clearInterval(removeText) } }, 1000); }
 <h1 class="writ-text">gold</h1> <h1 class="writ-text">golder</h1>

您已經清除了唯一的名為removeText (全局范圍)的setInterval ,這使得它適用於兩個文本。
使用像let const這樣的塊 scope 來解決

 let mySelector = document.querySelectorAll(".writ-text"); for (let l = 0; l < mySelector.length; l++) { let removeText = setInterval(function() { // Cut the last letter of the word and print the word after editing document.querySelectorAll(".writ-text")[l].textContent = document.querySelectorAll(".writ-text")[l].textContent.substr(0, document.querySelectorAll(".writ-text")[l].textContent.length - 1); // Check if the entire word has been deleted if (document.querySelectorAll(".writ-text")[l].textContent.length == 0) { clearInterval(removeText) } }, 1000); }
 <h1 class="writ-text">gold</h1> <h1 class="writ-text">golder</h1>

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM