简体   繁体   中英

Stop setInterval and start it again

I'm using this set interval function:

    function ticker(){
        setInterval(function(){
            $('.slide').fadeToggle();
        }, 5000);
    }

What I want to do is that when the user clicks on a div with onclick="topbartoggle" the setInterval function stops, and if he clicks again on it the setInterval function begins to work again:

function topbartoggle(){
    $('#top-bar').toggleClass('active');
    $('.top-bar-box').slideToggle();
    $('.top-bar-close').fadeToggle();   
}

Any idea on how to do this?

var tickerID = false; 
function ticker(){ 
    tickerID = setInterval(function(){ 
         $('.slide').fadeToggle(); 
    }, 5000); 
} 

To stop the ticker, use

clearInterval(tickerID);

To start it again, just call ticker();

EDIT: Understanding that you need to toggle the ticker, add this to your toggling function:

if(tickerID != false) {
    clearInterval(tickerID);
    tickerID = false;
} else { ticker(); }

setInterval returns a handle you can use to stop the interval, like this:

var myInterval = setInterval(function() { // myInterval should be global
    something();
}, 5000);

function stopInterval()
{
    clearInterval(myInterval);
}

So you can do like this:

<div onclick="stopInterval();anyOtherFunction();"></div> //anyOtherFunction could be any function you want.

Since you want to maintain the same delay, it's probably easiest to just keep the timer running:

var shouldTick = true;
var $slide = $('.slide');

setInterval(function () {
    
        $slide.fadeToggle();
    
}, 5000);

function topbartoggle() {
    
    $('#top-bar').toggleClass('active');
    $('.top-bar-box').slideToggle();
    $('.top-bar-close').fadeToggle();   
}

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