How to pause and resume jquery interval

前端 未结 3 895
粉色の甜心
粉色の甜心 2021-01-24 23:32

I have made a custom slider with jQuery. For this I have used setInterval function:

timer = setInterval(function() {},  8000);

But I cannot pau

3条回答
  •  面向向阳花
    2021-01-25 00:02

    I am not complete sure, that what you are asking for, is the right thing you are showing us... setInterval basically is pure native javascript and in my opinion not worth using! If you wan't to set your timeouts via jquery try this link: http://jchavannes.com/jquery-timer. You can find usages there...

    Now on to your problem... you need a state to check wether the slider has to slide or not... simply set a bool like this...

    var timer;
    var doSlide = false;
    var i = 0;
    
    function Slide(){
    
        timer = setTimeout(function(){
    
            if(doSlide == true){
                Slide();
                i++; // Same as i = i + 1
                console.log('Sliding');
    
                if(i == 3) AbortSlide(); /* Abort on third slide! Dont use this in your logic!*/
    
            } else if(doSlide == false){
                console.log('Sliding aborted untill next RunSlide() call!')
                clearTimeout(timer);
            }
    
        },1000);
    
    }
    
    function AbortSlide(){
        doSlide = false;
        i = 0;  // Resetting the count! Dont use this in your logic!
    }
    
    function RunSlide(){
        doSlide = true;
        Slide();
    }
    
    RunSlide();
    

    You could also empty the interval in the abort method:

    function AbortSlide(){
        doSlide = false;
        clearTimeout(timer);
        i = 0; // Resetting the count! Dont use this in your logic!
    }
    

    Here is a working fiddle i made for you to understand what timers and intervals are for: https://jsfiddle.net/q5qzmv68/7/

    Hope this helps! Cheers!

提交回复
热议问题