Check if interval works and vice versa

So, I have a web application with basic authentication.

When entering the system, the interval is set:

$("#login").click(function(e) { var interval = setInterval(function(){myFunction();}, 2000); }); 

Then, when I logged out, I need to stop the interval:

 $("#logout").click(function(e) { if(typeof interval !== 'undefined') clearInterval(interval); }); 

But it doesn’t work, I think the way to check if the interval exists is wrong ... I can set the interval so that it works when I log in, but I need to stop / clear it when I click on my Logging out and not ...

PS. im using the interval to check "myFunction" automatically every 2 seconds, but maybe there is another way to do this without the interval? THX

+5
source share
2 answers

Your interval variable should be declared in a higher scope, where it is available for both functions. Since you have it now, this is a local variable that ONLY exists in a specific call to your event handler function. So, when the next event handler is called, this previous variable no longer exists. You can also protect against successive clicks on the login:

 var interval; $("#login").click(function(e) { if (!interval) { interval = setInterval(function(){myFunction();}, 2000); } }); $("#logout").click(function(e) { clearInterval(interval); interval = null; }); 

And you do not need to check if interval undefined . You can simply call clearInterval() on it, and clearInterval() will protect against any invalid argument that you pass to it.

+10
source

Here is a simple example where your interval variable should be in the 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> 
+1
source

Source: https://habr.com/ru/post/1240664/


All Articles