Check if an Interval is running and viceversa
Here is a simple example where your interval variable should be in global scope for both click events.
<!DOCTYPE html>
<html>
<head>
<title></title>
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.7.1/jquery.min.js"></script>
<script type="text/javascript">
$(document).ready(function(){
function myFunction(){
var d = new Date();
var t = d.toLocaleTimeString();
document.getElementById("demo").innerHTML = t;
}
var interval;
$("#start").click(function(){
interval = setInterval(function(){
myFunction();
},2000);
});
$("#stop").click(function(){
clearInterval(interval);
});
});
</script>
</head>
<body>
<p id="demo"></p>
<button id="start">Start</button>
<button id="stop">Stop</button>
</body>
</html>
Your interval
variable needs to be declared at a higher scope where it is available to both functions. As you have it now, it is a local variable that ONLY exists within the particular invocation of your event handler function. So, when the next event handler is called, that previous variable no longer exists. You may also want to protect against successive clicks on login:
var interval;
$("#login").click(function(e) {
if (!interval) {
interval = setInterval(function(){myFunction();}, 2000);
}
});
$("#logout").click(function(e) {
clearInterval(interval);
interval = null;
});
And, you don't need to check to see if interval
is undefined
. You can just call clearInterval()
on it and clearInterval()
will protect against any invalid argument you pass it.