user2028856
user2028856

Reputation: 3183

jQuery stop function running several times over

I have a slider which I'm trying to pause and then resume when a user hovers over it:

    var run_state = true;
    var body_left = 0;
    function slider() {
        if (run_state == true) {
            $.get('http://mydomain.com/ajaxpage', function(data){
                var data_one = $(data).find('#container_sub').html();
                $('#container').append(data_one);
                body_left = body_left - 201;
                $('#container').animate({marginLeft: body_left+'px'}, 400);
                setTimeout(slider, 3000);
            });         
        }       
    }

    $('body').on('mouseover', '#container', function(){
        run_state = false;
    });
    $('body').on('mouseleave', '#container', function(){
        run_state = true;
        slider();
    });

I manage to pause the slider with mouseover but when it comes to mouseleave, the slider() function runs several times without stopping, causing several animations to run one after the other.

My question is, on mouseleavehow do I force the slider to finish the current animation, pause 3 seconds before running it again?

Thanks

Upvotes: 0

Views: 68

Answers (1)

Hüseyin BABAL
Hüseyin BABAL

Reputation: 15550

You can use setInterval for that;

var body_left = 0;
var myTimer;
function getContent() {
    $.get('http://mydomain.com/ajaxpage', function(data){
        var data_one = $(data).find('#container_sub').html();
        $('#container').append(data_one);
        body_left = body_left - 201;
        $('#container').animate({marginLeft: body_left+'px'}, 400);
        setTimeout(slider, 3000);
    }); 
}

function run() {
    myTimer = setInterval(function() {
        getContent();
    }, 3000);
}

$('#test').on('mouseover', function(){
    clearInterval(myTimer);

});
$('#test').on('mouseleave', function(){
    run();
});

You can see demo here : jsfiddle

Upvotes: 1

Related Questions