Hello I am trying to add countdown timer in my test engine. But I am unable to display that. If I am adding script in php page than its working but reloading and starting again. but if i am keeping java script file separate to avoid reload than unable to display timer. I am Adding code please suggest me suitable ans.Html and js are in separate file.
<script>
//define your time in second
var c=120;
var t;
timedCount();
function timedCount() {
var hours = parseInt( c / 3600 ) % 24;
var minutes = parseInt( c / 60 ) % 60;
var seconds = c % 60;
var result = (hours < 10 ? "0" + hours : hours) + ":" + (minutes < 10 ? "0" + minutes : minutes) + ":" + (seconds < 10 ? "0" + seconds : seconds);
document.getElementById("timer").innerHTML=result;
if(c == 0 ) {
//setConfirmUnload(false);
//$("#quiz_form").submit();
window.location="result.php?td=$tid";
}
c = c - 1;
t = setTimeout(function() {
timedCount()
},
1000);
}
</script>
//html
<div class='col-md-12 sub_top'>
<h4 style="color:#FF0000" align="center">
Time Remaining : <span id='timer'></span>
</h4>
</div>
The element ( document.getElementById("timer") )you were trying to find wasn’t in the DOM when the script ran.
Solution 1
To fix this you can execute the code on window.onload event
window.onload = function(){
timedCount();
}
Solution 2
execute code on DOMContentLoaded (document ready )
document.addEventListener('DOMContentLoaded', function(){
timedCount();
}, false);
Solution 3
Move your script just before the closing body tag.