JQuery restart setInterval

荒凉一梦 提交于 2019-12-30 12:57:52

问题


Sorry to be a bore but having trouble restarting a setInterval with a toggle function. I get to stop it - when needed, but I cannot get it to restart when the toggle "closes"

Here is my code

Set the setInterval

var auto_refresh = setInterval( function() { $('.holder').load('board.php'); }, 5000 );

Stop on toggle - BUT want it to start on the "reverse toggle"

$('.readmore').live('click',function() {
    $(this).next().slideToggle('slow');
    clearInterval(auto_refresh);
}, function() {
    var auto_refresh = setInterval( function() { $('.holder').load('board.php'); }, 5000 );
});

Help much appreciated, as is prob. very simple just I've never beed good at putting functions "within functions"


回答1:


Try:

$('.readmore').live('click',function() {
    $(this).next().slideToggle('slow');

    if(!auto_refresh ) {
        auto_refresh = setInterval( function() { $('.holder').load('board.php'); }, 5000 );
    }
    else {
        clearInterval(auto_refresh);
        auto_refresh = null;
    }
});

Or probably even better, use the state of the element to decide:

$('.readmore').live('click',function() {
    var $elem = $(this).next();

    if( $elem.is(':visible') ) {
        $elem.slideUp('slow');
        clearInterval(auto_refresh);
    }
    else {
        $elem.slideDown('slow');
        auto_refresh = setInterval( function() { $('.holder').load('board.php'); }, 5000 );

    }
});


来源:https://stackoverflow.com/questions/4758750/jquery-restart-setinterval

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!