Checking whether clearInterval has been called?

五迷三道 提交于 2019-12-02 20:10:58
Rich

The return value of setInterval is just a unique id you use to pass back to clearInterval. It's not a structured object with any additional information, nor does it get set to null when you call clearTimeout.

bob only contains an id of the interval used to clear it. When you call clearInterval, it gets the interval associated with that id and clears it. The id isn't changed at all.

see here for demonstration

example:

<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>

This will show you the interval's id (returned by setInterval earlier). If you know the interval's id is 1, you can just use clearInterval(1) to clear the interval. So your way of using setting bob to null is a good way of doing it. Just be sure that !bob doesn't return true if the bob happens to be 0. :D

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!