Reset setinterval on click

后端 未结 4 707
栀梦
栀梦 2021-02-09 12:48

I\'ve written this simple Carousel. At the moment I\'m using setInterval to run my nextSlide function at certain intervals. I want to defer the timer from running when a user cl

相关标签:
4条回答
  • 2021-02-09 13:19

    See:

    var IntID = setTimer();
    
    function setTimer(){
        i = setInterval(startSlider, 4000);
        return i;
    }
    
    function stopSlider() {
        clearInterval(IntID);
    }
    
    //Restart Timer
    
    // Option 1 make a restartSlider function and call it
    $("#button").click(restartSlider);
    function restartSlider(){
        IntID = setTimer();
    }
    
    //Option 2 create an anonymous function only for that click event.
    $("#button").click(function(){
        IntID = setTimer();
    });
    
    0 讨论(0)
  • 2021-02-09 13:20

    You can save the return value of setInterval in a variable to refer to it later - that way you can cancel it if you need to, or restart it.

    See this MDC article for more details.

    The basics are:

    intervalID = setInterval(flashText, 1000);
    
    //do something...
    
    clearInterval(intervalID);
    
    0 讨论(0)
  • 2021-02-09 13:23

    You could do something like this: http://jsbin.com/uzixi3/5/edit

    The interval part is here:

    var int = setInterval($.fn.nextSlide, 3000);
    $("#slideNavigation a").click(function() {
      clearInterval(int);
      setTimeout(function() {
        setInterval($.fn.nextSlide, 3000);
      }, 10000);
    });
    

    I made some other tweaks as well though, for example you can use a switch statement to make .nextSlide() much more readable and cheaper.

    Overall though, there's no reason to make these functions as extension methods on jjquery itself since they don't interact with objects, they can just be methods scoped to the closure like this: http://jsbin.com/uzixi3/6/edit

    If the methods were actually running on $('#slideContainer'), e.g. $('#slideContainer').nextSlide() and inside your methods you used this.animate() and this.css() it might make a bit more sense, just some thoughts that may help you get more flexible as you go.

    0 讨论(0)
  • 2021-02-09 13:27

    The above code really helped. Thanks Nick. I made a few minor adjustments so that once you clicked the function: the timer would stop, the function would execute, and then the timer initiates and resumes regular intervals.

    make sure you re-assign the var int to the new interval you create within the click function.

    var int = setInterval(change_slide, 5000);
    $("#div").click(function() {
        console.log('clicked');
      clearInterval(int);
      setTimeout(function() {
      int = setInterval(change_slide, 5000);
      });
    });
    
    0 讨论(0)
提交回复
热议问题