javascript - Uncaught TypeError: Cannot set property 'textContent' of null in Countdown Timer within Laravel
one text
I am running a timer in javascript for a php / laravel appication. in the console, I get a running error every second as the timer is running. I am not sure how to make the error go away. It does not effect the operation of the application as the timer does work. I also tried wrapping the code in a DOMContentLoaded function which had no effect. Can anyone let me know what I might have missed. Thank you. Here is the js code:
document.addEventListener("DOMContentLoaded", function() {
function startTimer(duration, display) {
let timer = duration, minutes, seconds;
setInterval(function () {
minutes = parseInt(timer / 60, 10);
seconds = parseInt(timer % 60, 10);
minutes = minutes < 10 ? "0" + minutes : minutes;
seconds = seconds < 10 ? "0" + seconds : seconds;
display.textContent = minutes + ":" + seconds;
if (--timer < 0) {
timer = duration;
alert('Your time has expired');
window.location.href="/student/exam";
}
}, 1000);
}
window.onload = function () {
let sixtyMinutes = 60 * 60,
display = document.querySelector('#time');
startTimer(sixtyMinutes, display);
};
});
And where I am calling the function inside the php file:
<div class="card-body">
<div class="row">
<div class="col-sm-4">
<h3>Time: 1 Hour</h3>
</div>
<div class="col-sm-4">
<h3 class="text-center">Timer : <span id="time" class="">60:00</span></h3>
</div>
<div class="col-sm-4">
<h3 class="text-right">Status: Pending</h3>
</div>
</div>
</div>
<!-- /.card-body -->
The line in question in the js code is:
display.textContent = minutes + ":" + seconds;
Again, any help appreciated. Thank you.
In Firefox, I get the following error:
Uncaught TypeError: display is null
startTimer http://lionsfieldtest.test/assets/js/custom.js:94
custom.js:94:13
Source