开发者

JQuery auto refresh (setInterval)

Hi folks not sure th开发者_JS百科e best way to do this - i.e. where to put the if's .. I have a div that loads a page and has a setInterval() function.

On the loaded page there is 1 button, What I want to acheive is when button #1 (loaded page) is clicked to stop the setInterval() and append a new div (position absolute) until button#2 (on the apended div) is clicked then to restart it. .. comprende?

Here is my "base" code

This is the action from the first button

 $('.replybutton').live('click',function(){
    $('.discussion').append('<div class="replyarea">some content in here plus "button number2</div>');
    });

This loads the page - initially

$('.discussion').load('board2.php');

And this is the refresh function

var auto_refresh = setInterval(
function()
    {
    $('.discussion').fadeOut().load('board2.php').fadeIn();

    }, 10000);

Failing anything - (but NOT preferred) I could use a toggle on the loaded page rather than the append used in the $('.replybutton').live('click',function(), but would still need to stop the refresh and restart it - based on the toggle, but I stress the toggle idea is not the preferred way.


I created an example for you at JSFiddle. Check it out here: http://jsfiddle.net/7YYV7/.

Code

var intervalId = 0;
intervalId = setInterval(fadeDiscussion, 3000);

$(function() {
    $('input[name=click]').bind('click', function() {
        clearInterval(intervalId);     

        $('.discussion').append('<div class="replyarea">some content in here plus <input type="button" name="save" value="save"></div>');    
    });

    $('input[name=save]').live('click', function() {
         intervalId = setInterval(fadeDiscussion, 3000);   
    });
});

var i = 1;
function fadeDiscussion () {
    console.log(i);
    $('.discussion').fadeOut().fadeIn();
    i++;
}


I think what you are looking for is the function clearInterval(). This will allow you to remove your interval based on the interval id (in your case auto_refresh).

Here are the docs: https://developer.mozilla.org/en/DOM/window.clearInterval

Now you could wrap you callback in a named function:

var reload = function(){
    $('.discussion').fadeOut().load('board2.php').fadeIn();
};

var auto_refresh = setInterval(reload, 10000);

$('button').click(function(){
    clearInterval(auto_refresh);
});
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜