So i have a web app with basic authentication.
When im logged in, an Interval is set:
$("#login").click(function(e) { var interval = setInterval(function(){myFunction();}, 2000); });
Then when im logged out i need to stop the interval:
$("#logout").click(function(e) { if(typeof interval !== 'undefined') clearInterval(interval); });
But it doesnt work, i think the way to check if an interval exist is wrong...i can set the interval so it is running when im logged in, but i need to stop/clear it when i click on my Logout button and it doesnt...
PS. im using the interval to check "myFunction" automatically every 2 seconds, but maybe there is another way to accomplish this without an interval? thx
The solution to this problem: Create a global counter that is incremented within your code performed by setInterval. Then before you recall setInterval, test if the counter is STILL incrementing. If so, your setInterval is still active.
To check if a setInterval timer is running and stop it with JavaScript, we can call clearIntveral with the timer variable. to add a button. to call setInterval with a callback that runs every 2 seconds. Then we select the button with querySelector .
This property can be used in the callback of the setInterval() function, as it would get immediately executed once and then the actual setInterval() with this function will start after the specified delay.
The setInterval() function is commonly used to set a delay for functions that are executed again and again, such as animations. You can cancel the interval using clearInterval() . If you wish to have your function called once after the specified delay, use setTimeout() .
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With