我正在尝试创建倒计时器,如果用户在中间停止计时器,则在完成时间后提交表单,然后我必须计算剩余时间。这是我的代码。
<html>
<head>
<meta charset="UTF-8">
<title></title>
<script type="text/javascript">
var total_seconds = 600;
var c_minutes=parseInt(total_seconds/60);
var c_seconds=parseInt(total_seconds%60);
var hours=parseInt(total_seconds/3600);
function CheckTime(){
document.getElementById('time-left').innerHTML='Time Left: '+hours+' hours '+c_minutes+' min '+c_seconds+' sec';
if(total_seconds<=0){
alert("oops no time left");
setTimeout('document.form.submit()',1);
}else{
total_seconds=total_seconds-1;
c_minutes=parseInt(total_seconds/60);
c_seconds=parseInt(total_seconds%60);
hours=parseInt(total_seconds/3600);
setTimeout("CheckTime()",1000);
}
}
var timeout = setTimeout("CheckTime()",1000);
setInterval(function() {
console.log('Time left: '+getTimeLeft(timeout)+'s');
}, 2000);
function getTimeLeft(timeout) {
return Math.ceil((timeout._idleStart + timeout._idleTimeout - Date.now()) / 1000);
}
</script>
</head>
<body>
<h1>Countdown Timer</h1>
<div id="time-left"> </div>
<br/><br/>
<form method="post" name="form" action="timer.php"></form>
<button onclick="getTimeLeft()">Stop</button>
</body>
</html>
答案 0 :(得分:1)
感谢Leopard,我明白了。
<html>
<head>
<meta charset="UTF-8">
<title></title>
<script type="text/javascript">
var total_seconds = 600;
var c_minutes=parseInt(total_seconds/60);
var c_seconds=parseInt(total_seconds%60);
var hours=parseInt(total_seconds/3600);
function CheckTime(){
document.getElementById('time-left').innerHTML='Time Left: '+hours+' hours '+c_minutes+' min '+c_seconds+' sec';
if(total_seconds<=0){
alert("oops no time left");
setTimeout('document.form.submit()',1);
}else{
total_seconds=total_seconds-1;
c_minutes=parseInt(total_seconds/60);
c_seconds=parseInt(total_seconds%60);
hours=parseInt(total_seconds/3600);
console.log(total_seconds);
setTimeout("CheckTime()",1000);
}
}
setTimeout("CheckTime()",1000);
</script>
</head>
<body>
<h1>Countdown Timer</h1>
<div id="time-left"> </div>
<br/><br/>
<form method="post" name="form">
<input type="submit" name="sub" id="submt" value="Save">
</form>
</body>
</html>
答案 1 :(得分:0)
您可以简单地使用变量total_seconds
来获取剩余时间(以秒为单位),因为它已经在seconds
中并且每两秒后更新一次。
var timeout = setTimeout("CheckTime()",1000);
setInterval(function() {
console.log('Time left: '+total_seconds+'s');
}, 2000);