倒数计时器:无法设置 属性 'textContent' 为 null

Countdown-Timer: Cannot set property 'textContent' of null

我在一些倒计时脚本中遇到了一些错误。在这里找不到解决方案。错误消息每秒产生 1 个错误:

Uncaught TypeError: Cannot set property 'textContent' of null
at (index):181
(anonymous) @ (index):181
setInterval (async)
(anonymous) @ (index):179

这是定时器的脚本:

<script type="text/javascript">

var timeleft = 45;
var downloadTimer = setInterval(function(){

timeleft--;
document.getElementById("countdowntimer").textContent = timeleft;
document.getElementById("countdowntimer").style.color = "white";

if(timeleft <= 0)
    clearInterval(downloadTimer);
},1000);

</script>

您的 html(根据您的评论)无效 (</span class="timer">)。此外,还可以简化代码。

countDownForNOfTicks(5);

function countDownForNOfTicks(nOfTicks) {
  document.querySelector("#countdowntimer").textContent = nOfTicks--;
  // [do more things if necessary]
  if (nOfTicks >= 0) {
    return setTimeout(() => countDownForNOfTicks(nOfTicks), 1000);
  }
  return refresh();
}

function refresh() {
  document.querySelector("div.timer").textContent += " DONE";
}
<div class="timer">Refreshing in 
 <span id="countdowntimer">45</span> seconds
</div>