0

I got some errors with a little countdown script. Can't find a solution here. The error message produces 1 error every second:

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

This is the script for the timer:

<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>
  • What is `textContent` element in HTML? – Ankit Agarwal Sep 03 '18 at 13:23
  • 1
    There's no element with id `countdowntimer` in the DOM. – Andreas Sep 03 '18 at 13:24
  • 3
    Possible duplicate of [Why does jQuery or a DOM method such as getElementById not find the element?](https://stackoverflow.com/questions/14028959/why-does-jquery-or-a-dom-method-such-as-getelementbyid-not-find-the-element) – Andreas Sep 03 '18 at 13:25
  • Are you sure your document has an element with id "countdowntimer"? If so, it might not have loaded yet, maybe try surrounding your code with `document.addEventListener("DOMContentLoaded", function(event) { //CODE }` – Sam Sep 03 '18 at 13:25
  • `
    Refreshing in 45 seconds
    ` is where I try to load the script. It works but creates those errors
    – DasNerdwork Sep 03 '18 at 13:32
  • Is your `script` after or before the HTML? – ᔕᖺᘎᕊ Sep 03 '18 at 13:46

1 Answers1

0

Your html (as per your comment) is invalid (</span class="timer">). Furthermore, the code can be simplified.

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>
KooiInc
  • 119,216
  • 31
  • 141
  • 177