我用一个小倒计时脚本得到了一些错误。在这里找不到解决方案。错误消息每秒产生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>