[英]setInterval Javascript MVC2
I am trying to use setInterval to calculate time left, here is my script: 我正在尝试使用setInterval来计算剩余时间,这是我的脚本:
var intervalID;
function StartTimer() {
var intervalID = setInterval(function () {
var settimmer = 100; // $('#timeleft').val();
var seconds = 0;
seconds++;
if (seconds >= 60) {
settimmer--;
seconds = 0;
$('#timeleft').val(settimmer);
}
}, 1000);
}
function StopTimer() {
clearInterval(intervalID);
}
<input type="text" size="8" id="timeleft" name="timeleft" value="100" />
<button onclick="StartTimer();">
start</button>
<button onclick="StopTimer();">
Stop</button>
I does not work, however when I use the following script, it works but don't know how to stop it: 我无法工作,但是当我使用以下脚本时,它可以工作,但不知道如何停止它:
var settimmer = 100;
var seconds = 0;
$(function () {
window.setInterval(function () {
seconds++;
if (seconds >= 60) {
settimmer--;
seconds = 0;
$('#timeleft').val(settimmer);
}
}, 1000);
});
Thanks in advance. 提前致谢。
您在StartTimer()
函数中重新声明intervalID
,然后删除var
。
The problem is the scope of variable. 问题是变量的范围。 You re-declaring intervalID in the function StartTimer, and it will cover the global variable 'intervalID' and only be used in this function. 您在函数StartTimer中重新声明了intervalID,它将覆盖全局变量'intervalID',仅在此函数中使用。 In fact, the variable 'intervalID' outside is not valued. 实际上,外面的变量“ intervalID”没有值。 So when you use clearInterval(intervalID), it certainly does not work. 因此,当您使用clearInterval(intervalID)时,它肯定不起作用。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.