I have the following ajax page. The form should be submitted and the timer should be restart counting down when the timer expires or button is clicked.
For some reason the timer is not reset and goes minus. Can someone tell me how to fix this?(The code is standalone, you can copy/paste ans test it, then run it on server)
test.htm:
<html>
<head>
<script type="text/javascript" src="http://mootools.net/download/get/mootools-core-1.3-full-compat.js"></script>
</head>
<body>
<div id="container">
<form id="form" name="form" action="test.htm" method="post">
Remaining time: <input type="text" name="clock" size="4">seconds
<input type="submit" value="submit" ID="questionSubmit">
</form>
<script type="text/javascript">
var timeLeft = 10;
function startClock() {
timeLeft--;
document.form.clock.value = timeLeft;
if(timeLeft == 0) {
sendForm();
}
else {
setTimeout("startClock()", 1000);
}
}
setTimeout("startClock()", 1000);
</script>
<script type="text/javascript">
function handleSubmit(e) {
e = new Event(e).stop();
sendForm();
}
function sendForm() {
$('form').set('send', {onComplete: function(response) {
$('container').set('html', response);
$('questionSubmit').addEventListener('click', handleSubmit, false);
setTimeout("startClock()", 1000);
}});
//Send the form.
$('form').send();
}
$('questionSubmit').addEventListener('click', handleSubmit, false);开发者_运维知识库
</script>
</div>
</body>
</html>
As I mentioned in my comment, you should use <=0
. As you replied, sendForm()
is then called every second. This doesn't make sense, so I suspect there's something else going on
My second observation is that you're never resetting timeLeft
. A good place for this would be following the call to sendForm
Following additions fixed it:
<input id="timeLeft" type="hidden" value="<?php echo $time; ?>" />
...
function sendForm() {
/.../
timeLeft = document.getElementById('timeLeft').value;
/.../
}
精彩评论