Question

I'm new to JavaScript and I'm having problems with this script. it's part of a web game and the script is suppose to refresh the page until the player wins or loses. for some reason it doesn't stop refreshing, I put an alert function to check if the functions works, and i get the alerts but it's still continue refreshing the page. what am i doing wrong?

var t;

$(document).ready(function () {
    intervals();
});
function intervals() {
    t = self.setInterval('refreshData()', 10000);
}
function youWin() {
    var f = $('#status:contains("YOU ARE THE WINNER!")');
    if (f.length > 0) {
        alert("YOU ARE THE WINNER!");
        t = clearInterval(t);
    }
}
function youlose() {
    var f = $('#status:contains("You lost!")');
    if (f.length > 0) {
        alert("You lost!");
        t = clearInterval(t);
    }
}
function refreshData() {
    $('#ajaxGame').load('RefreshCurrentPlayerServlet #ajaxGame');
    youWin();
    youlose();
}
Was it helpful?

Solution

You need to fix the reference to self and fix the .load() call.

.load() is asynchronous so it does not complete before you call youWin() and youLose() right after it. You need a completion function so you can check winning or losing after the .load() completes successfully.

refreshData() should be structured like this:

function refreshData() {
    $('#ajaxGame').load('RefreshCurrentPlayerServlet #ajaxGame', function() {
        youWin();
        youlose();
    });
}

You also should change this:

t= self.setInterval('refreshData()',10000);

to this:

t = window.setInterval(refreshData, 10000);

I don't see that self was even defined so that could have also been causing your problem and you should use the function reference directly rather than put in a string.

And, as a cleanup issue, you should change both occurences of this:

t = clearInterval(t);

to this:

clearInterval(t);

Here's a cleaned up version of the code that also eliminates global variables and unnecessary function definitions:

$(document).ready(function() {
    var t = window.setInterval(function() {
        $('#ajaxGame').load('RefreshCurrentPlayerServlet #ajaxGame', function() {
            youWin();
            youlose();
        });
    }, 10000);

    function youWin()  {
        if ($('#status:contains("YOU ARE THE WINNER!")').length) {
            alert("YOU ARE THE WINNER!");
            clearInterval(t);
        }
    }

    function youlose() {
        if ($('#status:contains("You lost!")').length) {
            alert("You lost!");
            clearInterval(t);
        }
    }

});
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top