在匿名函数中停止计时器 jquery
Stopping timer in an anonymous function jquery
我有一个计时器,它会在场景加载时启动 运行。我试图阻止它,但我认为问题是因为它在匿名函数中。有什么方法可以通过按钮停止它吗?
$(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>
您需要计时器的 ID,因为您正在保存对计时器的引用。
所以下面的代码会停止计时器:
window.clearInterval(timer);
将点击处理程序移到匿名函数中,使其与 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>
我有一个计时器,它会在场景加载时启动 运行。我试图阻止它,但我认为问题是因为它在匿名函数中。有什么方法可以通过按钮停止它吗?
$(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>
您需要计时器的 ID,因为您正在保存对计时器的引用。
所以下面的代码会停止计时器:
window.clearInterval(timer);
将点击处理程序移到匿名函数中,使其与 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>