我创建了一个计时器,当用户插入一个安全代码(即569)时,该计时器可以停止。如何在插入代码时停止计时器,因为现在它只显示"祝贺,任务完成!"
function startTimer(duration, display) {
var timer = duration, minutes, seconds;
setInterval(function () {
minutes = parseInt(timer / 60, 10)
seconds = parseInt(timer % 60, 10);
minutes = minutes < 10 ? "0" + minutes : minutes;
seconds = seconds < 10 ? "0" + seconds : seconds;
display.textContent = minutes + ":" + seconds;
if (--timer < 0) {
document.getElementById("text").innerHTML = "You're dead";
}
}, 1000);
}
window.onload = function () {
var Minutes = 60 * 0.5,
display = document.querySelector('#time');
startTimer(Minutes, display);
};
function StopFunction() {
var code;
var rightcode=569;
code = document.getElementById("icode").value;
text = (code==rightcode) ? "Congratulation, mission complete!":"Sorry, wrong code, try again!";
if(code==rightcode){
display = document.getElementById("time").innerHTML = "Stop timer";}
document.getElementById("text2").innerHTML =text;
}
&#13;
.btn {
border: none;
color: white;
padding: 14px 28px;
font-size: 16px;
cursor: pointer;
}
.success {background-color: #4CAF50;} /* Green */
.success:hover {background-color: #46a049;}
&#13;
<div id="text">You have <span id="time"></span> minutes left!</div>
<p id="text2"></p>
<br>
<p>Enter the code:</p>
<input id="icode"/>
<button class="btn success" onclick="StopFunction()">Check code</button>
&#13;
答案 0 :(得分:0)
以下代码应该适合您
var interval;
function startTimer(duration, display) {
var timer = duration, minutes, seconds;
interval=setInterval(function () {
minutes = parseInt(timer / 60, 10)
seconds = parseInt(timer % 60, 10);
minutes = minutes < 10 ? "0" + minutes : minutes;
seconds = seconds < 10 ? "0" + seconds : seconds;
display.textContent = minutes + ":" + seconds;
if (--timer < 0) {
document.getElementById("text").innerHTML = "You're dead";
}
}, 1000);
}
window.onload = function () {
var Minutes = 60 * 0.5,
display = document.querySelector('#time');
startTimer(Minutes, display);
};
function StopFunction() {
var code;
var rightcode=569;
code = document.getElementById("icode").value;
text = (code==rightcode) ? "Congratulation, mission complete!":"Sorry, wrong code, try again!";
if(code==rightcode){
display = document.getElementById("time").innerHTML = "Stop timer";}
document.getElementById("text2").innerHTML =text;
clearInterval(interval);
}