swa*_*jak 34 javascript settimeout intervals setinterval
鉴于此代码:
bob = setInterval(function, 1000);
clearInterval(bob);
Run Code Online (Sandbox Code Playgroud)
现在有办法知道该间隔是否已被清除?
目前,我通过取消' bob'来跟踪这个问题,但是如果我的额外代码行是不必要的,我很好奇:
clearInterval(bob);
bob = null;
if (!bob) itIsCleared();
Run Code Online (Sandbox Code Playgroud)
谢谢!
Ric*_*ich 35
返回值setInterval只是您用来传递回的唯一IDclearInterval.它不是具有任何附加信息的结构化对象,也不会在您调用时设置为null clearTimeout.
所以这是一个很晚的答案,但如果你这样做
this.myInterval = setInterval(....);
this.myInterval = clearInterval(this.myInterval);
Run Code Online (Sandbox Code Playgroud)
它将强制变量myInterval未定义,因此您可以通过执行以下操作来检查间隔的清除情况if(!this.myInterval)
bob只包含用于清除它的间隔的id.当您调用clearInterval时,它会获取与该id相关联的时间间隔并将其清除.id根本没有改变.
例:
<html>
<head>
<title>Javascript clearInterval</title>
</head>
<body onload="startInterval();">
<center>
<div id="myTime"></div>
<input type="button" value="start Interval" onclick="startInterval();" />
<input type="button" value="stop Interval" onclick="stopInterval();" />
</center>
<script language="javascript">
var interval;
function startInterval()
{
// setInterval of 1000 milliseconds i.e. 1 second
// to recall the startTime() method again n again
interval = setInterval("startTime();", 1000);
}
function startTime()
{
// Date object to get current time
var timeFormat = new Date();
// set the current time into the HTML div object.
document.getElementById('myTime').innerHTML = timeFormat.toLocaleTimeString();
}
function stopInterval() //***********IMPORTANT FUNC******************
{
// clearInterval to stop the setInterval event
alert(interval);
clearInterval(1);
}
</script>
</body>
</html>
Run Code Online (Sandbox Code Playgroud)
这将显示间隔的id(之前由setInterval返回).如果您知道间隔的id为1,则可以使用clearInterval(1)清除间隔.因此,将bob设置为null的方法是一种很好的方法.请确保!如果bob恰好为0,bob不会返回true:D