Monday, May 20, 2024
 Popular · Latest · Hot · Upcoming
137
rated 0 times [  143] [ 6]  / answers: 1 / hits: 48213  / 9 Years ago, fri, january 15, 2016, 12:00:00

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


More From » jquery

 Answers
3

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.


[#63726] Tuesday, January 12, 2016, 9 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
neilshamarh

Total Points: 181
Total Questions: 94
Total Answers: 104

Location: Guadeloupe
Member since Sat, Aug 22, 2020
4 Years ago
;