循环中的 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>

您已经清除了唯一的 setInterval 命名为 removeText(全局范围),这使得它适用于两个文本。
使用像 let const 这样的块范围来计算

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>