I implemented a countdown timer in typescript on the homepage of my website. However, when I navigate to another page, I encounter a console error every second.
.TS
countDown() {
var countDownDate = new Date("Jan 1, 2022 00:00:00").getTime();
// Update the count down every 1 second
var x = setInterval(function () {
var now = new Date().getTime();
// Find the distance between now an the count down date
var distance = countDownDate - now;
var days = Math.floor(distance / (1000 * 60 * 60 * 24));
var hours = Math.floor((distance % (1000 * 60 * 60 * 24)) / (1000 * 60 * 60));
var minutes = Math.floor((distance % (1000 * 60 * 60)) / (1000 * 60));
var seconds = Math.floor((distance % (1000 * 60)) / 1000);
// Display the result in an element with id="demo"
var contadorElement = document.getElementById("contador") as HTMLElement; // <- Line 37
contadorElement.innerHTML = days + "d " + hours + "h "
+ minutes + "m " + seconds + "s ";
if (distance < 0) {
clearInterval(x);
contadorElement.innerHTML = "EXPIRED";
}
}, 1000);
}
.HTML
<p id="contador" style="font-size:30px"></p>
The code functions properly under 'localhost:4200/', however, if I visit 'localhost:4200/anotherStuff' (for example), I receive a console error each second:
core.js:6456 ERROR TypeError: Cannot set properties of null (setting 'innerHTML')
at home.component.ts:37
at timer (zone.js:2561)
at ZoneDelegate.invokeTask (zone.js:406)
at Object.onInvokeTask (core.js:28661)
at ZoneDelegate.invokeTask (zone.js:405)
at Zone.runTask (zone.js:178)
at invokeTask (zone.js:487)
at ZoneTask.invoke (zone.js:476)
at data.args.<computed> (zone.js:2541)
Any insights or suggestions?