我需要在02.00到0.00之间停止计时。但它在-1.59停止或开始减少。在angular typescript我写了上面的代码。我做错了什么:
<html>
<body>
<input type="text" name="otp" placeholer="Enter your otp"/>
<div>Time left = <span id="timer"></span></div>
</body>
</html>
IN Angular打字稿:
callMyCount(){
document.getElementById('timer').innerHTML ="02" + ":" + "00";
var myTimer=setInterval(startTimer,1000);
function startTimer() {
var presentTime = document.getElementById('timer').innerHTML;
var timeArray = presentTime.split(/[:]+/);
var m = parseInt(timeArray[0]);
var s = checkSecond((parseInt(timeArray[1]) - 1));
if(s==59){m=m-1}
if(m<0 && s==59){alert("Timeout for otp");
clearTimeout(myTimer);}
document.('timer').innerHTML = m + ":" + s;
}
function checkSecond(sec) {
if (sec < 10 && sec >= 0) {sec = "0" + sec};
if (sec < 0) {sec = "59"};
return sec;
}
}
答案 0 :(得分:0)
使用内部setTimeout
执行递归调用并仅计数秒数,您可以做得更简单:
let timerOn = true;
function timer(remaining) {
var m = Math.floor(remaining / 60);
var s = remaining % 60;
m = m < 10 ? '0' + m : m;
s = s < 10 ? '0' + s : s;
document.getElementById('timer').innerHTML = m + ':' + s;
remaining -= 1;
if(remaining >= 0 && timerOn) {
setTimeout(function() {
timer(remaining);
}, 1000);
return;
}
if(!timerOn) {
// Do validate stuff here
return;
}
// Do timeout stuff here
alert('Timeout for otp');
}
timer(120);
<input type="text" name="otp" placeholer="Enter your otp"/>
<div>Time left = <span id="timer"></span></div>
timerOn
var仅用于以编程方式停止倒计时。如果加载另一页,则无用。