简体   繁体   中英

How to do a clear interval in javascript?

My Code:

$(function() {

     $('a.startSlideshow').click(function() {     
          startSlideShow = window.setInterval(function() { slideSwitch() }, 1000);
     });


     $('a.next').click(function() {     
          if (startSlideShow) {
               clearInterval(startSlideShow);
          }
          nextSlide();
     });

});

My Intention:

If a user clicks the startSlideshow link the slideshow function is executed every 1 seconds.

If the user clicks the next link, the slideshow function is stopped IF IT HAS ALREADY BEEN EXECUTED.

To be able to detect this, I stored the set interval as a variable. However when I check for it:

          if (startSlideShow) {
               clearInterval(startSlideShow);
          }

It doesn't work. Right now my code works if I click on the start slideshow link before clicking next. But if the slideshow function was never started (ie I never clicked that link first but clicked next from the start) the code fails.

basically this is causing the code to break for some reason when startSlideshow var hasn't been defined:

      if (startSlideShow) {
           clearInterval(startSlideShow);
      }

I did try other ways of checking to see if that variable has been set, but all failed. How to solve this?

I believe you have a scope issue:

$(function() {
     var startSlideShow;

     $('a.startSlideshow').click(function() {     
          startSlideShow = window.setInterval(function() { slideSwitch() }, 1000);
     });


     $('a.next').click(function() {     
          if (startSlideShow) {
               clearInterval(startSlideShow);
          }
          nextSlide();
     });

});

Define the variable outside of the click functions.

Declare startSlideShow before your first handler:

var startSlideShow = null;

And clear it later:

if (startSlideShow) {
    window.clearInterval(startSlideShow);
    startSlideShow = null;
} 

That is because you do no declare startSlideShow , so it doesn't exist until the start function is run. At that point, it becomes a global variable with a value.

You should include it in a closure and declare it with var .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM