检查clearInterval是否已经叫什么名字?
-
16-09-2019 - |
题
鉴于这种代码:
bob = setInterval(function, 1000);
clearInterval(bob);
现在有没有办法知道,如果该区间已被清除?
目前,我跟踪这个自己,通过取消“bob
”,但我很好奇,如果我的额外的代码行是不必要的:
clearInterval(bob);
bob = null;
if (!bob) itIsCleared();
谢谢!
解决方案
setInterval
的返回值只是一个唯一ID 您使用回传给clearInterval
。它不与任何附加信息的结构化对象,也不会被置当你调用clearTimeout
为null。
其他提示
鲍勃只包含用于清除它的时间间隔的一个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>
这将告诉您的间隔的ID(由setInterval的更早返回)。如果您知道间隔的id是1,你可以我们可以使用clearInterval(1)清除的时间间隔。所以,你的使用环境鲍勃空的方式是这样做的一个很好的方式。只是要确保,如果鲍勃恰好是鲍勃没有返回true 0:d
不隶属于 StackOverflow