我有一个计时器,在场景加载时开始运行。我试图阻止它,但我认为问题是因为它是一个匿名函数。有没有办法可以通过按钮停止它?
$(function () {
var timer;
var secs = 0;
var mins = 0;
var timeField = document.getElementById("time");
timeField.innerHTML = "00:00";
function update(){
if(secs == 59){
mins++;
secs = 0;
}
else {
secs++;
}
if(secs<10){
timeField.innerHTML = mins + ':0' + secs;
}
else {
timeField.innerHTML = mins + ':' + secs;
}
}
function start(){
timer = setInterval(function() {update()}, 1000);
}
start();
});
$("#1").click(function(){
$(this).hide();
});
<body window.onload=function() {start();}>
<div id="time"><span>00:00</span></div>
</body>
<button id="1"> One</button>
答案 0 :(得分:1)
您需要计时器的ID,因为您要保存对计时器的引用。
因此以下代码将停止计时器:
window.clearInterval(timer);
答案 1 :(得分:1)
将单击处理程序移动到匿名函数中,以使其与timer
变量具有相同的范围。
然后您可以在点击处理程序中添加它:
clearInterval(timer);
<强>段强>
$(function() {
var timer;
var secs = 0;
var mins = 0;
var timeField = document.getElementById("time");
timeField.innerHTML = "00:00";
function update() {
if (secs == 59) {
mins++;
secs = 0;
} else {
secs++;
}
if (secs < 10) {
timeField.innerHTML = mins + ':0' + secs;
} else {
timeField.innerHTML = mins + ':' + secs;
}
}
function start() {
timer = setInterval(function() {
update()
}, 1000);
}
start();
$("#1").click(function() {
$(this).hide();
clearInterval(timer);
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<body window.onload=function() {start();}>
<div id="time"><span>00:00</span>
</div>
</body>
<button id="1">One</button>