Alek Arsovski
Alek Arsovski

Reputation: 349

Clear Interval not working ( Tried all other answers )

So I have this function to check when a opponent is connected. Everything works, except the clearInterval thing... I tried adding window.setInterval and window.clearInterval . I tried adding self. too...

$(document).ready(function() {

    var waitForOpponent = setInterval(checkUserStatus, 2000);

    function checkUserStatus() {
    $('#user').load('checkuser.php?randval='+ Math.random());
        $("#user").ajaxStop(function(){
       if(document.getElementById("user").innerHTML!=""){
                clearInterval(waitForOpponent);
        opponentConnected();
       }
    });
    }

});

I also tried to go like this:

var waitForOpponent;

function check() { waitForOpponent = setInterval(checkUserStatus, 2000); }

check();

Please help me out guys.. I tried everything...

Upvotes: 0

Views: 259

Answers (1)

Kevin B
Kevin B

Reputation: 95018

Get rid of ajaxStop and use the success callback of the .load.

$('#user').load('checkuser.php?randval='+ Math.random(),function(){
    if(document.getElementById("user").innerHTML!=""){
        clearInterval(waitForOpponent);
        opponentConnected();
    }
});

if the requests are taking longer than 2 seconds, ajaxstop will never be called.

A better alternative in my opinion is to not use setInterval:

function checkUserStatus() {
    $('#user').load('checkuser.php?randval='+ Math.random(),function(){
        if(document.getElementById("user").innerHTML!=""){
            opponentConnected();
            return; // exit
        }
        setTimeout(checkUserStatus,2000); // continue after 2 seconds
    });
}
checkUserStatus(); // start it up

this prevents the ajax requests from piling up on slow connections or on timeouts.

Upvotes: 2

Related Questions