Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Check if an Interval is running and viceversa

Tags:

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

like image 417
xnanitox Avatar asked Jan 15 '16 06:01

xnanitox


People also ask

How do I know if setInterval is running?

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.

How do I know if jquery is setInterval running?

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 .

Does set interval call immediately?

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.

How do you start and stop an interval?

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() .


1 Answers

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.

like image 124
jfriend00 Avatar answered Oct 14 '22 05:10

jfriend00