28

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

RockyK
  • 403
  • 9
  • 12
xnanitox
  • 475
  • 1
  • 6
  • 9

2 Answers2

51

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.

jfriend00
  • 683,504
  • 96
  • 985
  • 979
  • well its need to check if defined as overwise it will drop error in concole – Gorodeckij Dimitrij May 15 '20 at 00:41
  • @GorodeckijDimitrij - Check where? – jfriend00 May 15 '20 at 02:06
  • I dont know, not yet expert in js, however on my embed version (es5) have situation then loading embed widget who start timer, and sometimes check comes before timer started and its a timer on parent so they clash, i try to delete it on load but it keep saying undefined if its hapening before its start. Avoid this by creating diferent names of timers and just pause each others depends on widget status - loaded as normaly or in popup – Gorodeckij Dimitrij May 15 '20 at 10:27
  • 1
    @GorodeckijDimitrij - It sounds like you have something a bit different than this code. If you want help with it, please post your own question, showing your own code. – jfriend00 May 15 '20 at 14:17
  • WARNING: You should also be careful at setting the variable on a higher scope. Say you log in twice, then the ID will be overwritten, and you don't get to clear the first interval. The check is to see if there is a thread running other intervals. I'd like to know as well. @GorodeckijDimitrij The interval is running in an async CPU-thread. The variable only contains an id of the interval. – agiopnl Mar 10 '22 at 17:58
  • With a global handler, the second time you call "clearInterval(myhandler)" will throw an error in the console. If you cleared before with clearInterval(myhandler) you also need to add "interval = null;" after that. Then you can check "if (myhandler) clearInterval(myhandler)" without error in the console. – Thomas Jan 19 '23 at 15:49
  • @Thomas - It's unclear to me what you mean here. My code already sets `interval = null` after calling `clearInterval(interval)`. And, `clearInterval(null)` does not log anything in the console for me in Chrome so I don't think there's a need to check the `interval` variable before calling `clearInterval(interval)` to protect against `null` as the value. So, what exactly are you suggesting needs to change? – jfriend00 Jan 20 '23 at 00:15
  • @jfriend00 your answer is ok. So I got the error in another case. But (in your case) if you click second time on #logout the value of interval is null and (I thought) that will throw an error in the console – Thomas Jan 24 '23 at 12:31
  • @Thomas - `clearInterval(null)` does not cause any problem. If it bothered you, you could check for `null` first, but that is not necessary. – jfriend00 Jan 24 '23 at 21:49
1

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>
jameshwart lopez
  • 2,993
  • 6
  • 35
  • 65