Moritz
Moritz

Reputation: 766

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);
});

Upvotes: 0

Views: 170

Answers (2)

Satish Kumar sonker
Satish Kumar sonker

Reputation: 1288

In order to make globle variable, declare the variable name without var keyword.

As below

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

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

Upvotes: 0

Tushar
Tushar

Reputation: 87203

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);
});

Upvotes: 3

Related Questions