Search code examples
jqueryintervalsmouseleavemouseout

Interval doesn't stop on mouseout


The interval "myInterval" won't stop if I move the mouse out of the element which triggers the interval function before. Why doesn't it stop?

$(".postimagepic").mouseenter(function () {
    var link = $("#blurpost").attr("src").split("/").pop().split(".", 1)[0];
    var myInterval = setInterval(function () {
        $.ajax({
            url: 'asdf.php',
            type: 'post',
            data: {
                'user': 'yy',
                'topost': link
            },
            success: function () {

            }
        });
    }, 1000);
}).mouseout(function () {
    clearInterval(myInterval);
});

Solution

  • The variable myInterval is private to the mouseenter callback function and hence not accessible outside of that function. To make it accessible from mouseout callback function, declare the variable outside of the function.

    var myInterval; // Define it here to make it global
    
    $(".postimagepic").mouseenter(function () {
        var link = $("#blurpost").attr("src").split("/").pop().split(".", 1)[0];
        myInterval = setInterval(function () {
            $.ajax({
                ...
            });
        }, 1000);
    }).mouseout(function () {
        // Accessible here
        clearInterval(myInterval);
    });
    

    I'll also suggest to use hover() instead of mouseenter and mouseout events.

    var myInterval; // Define it here to make it global
    
    $(".postimagepic").hover(function () {
        var link = $("#blurpost").attr("src").split("/").pop().split(".", 1)[0];
        myInterval = setInterval(function () {
            $.ajax({
                ...
            });
        }, 1000);
    }, function () {
        clearInterval(myInterval);
    });