Aso.S Aso.S - 1 month ago 8
Javascript Question

how do i auto-submit the form when the timer comes to 00:00:00

I have used a countdown timer in my online examination website,the timer is shown via javaScript but problem is that after the 00:00:00 the timer shows negative time.I just want to stop the timer at 00:00:00 and submit a form when the time is over.below is the code that accurately displaying me the timer.

<?php
// Upon starting the section
session_start();
$_SESSION['TIMER'] = time() + 600; // Give the user Ten minutes
?>
<script type="text/javascript">
var TimeLimit = new Date('<?php echo date('r', $_SESSION['TIMER']) ?>');

</script>


<script type="text/javascript">
function countdownto() {
var date = Math.round((TimeLimit-new Date())/1000);
var hours = Math.floor(date/3600);
date = date - (hours*3600);
var mins = Math.floor(date/60);
date = date - (mins*60);
var secs = date;
if (hours<10) hours = '0'+hours;
if (mins<10) mins = '0'+mins;
if (secs<10) secs = '0'+secs;
document.body.innerHTML = hours+':'+mins+':'+secs;
setTimeout("countdownto()",1000);

if((hours==00)&&(mins==00)&&(secs==00))
document.alert("time is over");
}

countdownto();

</script>

Answer

I assume that your form has an ID attribute with this value yourForm.

// HTML
<form id="yourForm">[...]</form>

// JS
if((hours==00)&&(mins==00)&&(secs==00)) {
  document.getElementById('yourForm').submit();
} else {
  setTimeout("countdownto()", 1000);
}

Note: Remove your setTimeout("countdownto()", 1000); before the if statement

Alternative way.

You could kill the timeout with clearTimeout()

var myTimeout = setTimeout("countdownto()", 1000);

if((hours==00)&&(mins==00)&&(secs==00)) {
  clearTimeout(myTimeout);
  document.getElementById('yourForm').submit();
}

clearTimeout documentation

Comments