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();
}
You need to fix the reference to
selfand fix the.load()call..load()is asynchronous so it does not complete before you callyouWin()andyouLose()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:You also should change this:
to this:
I don’t see that
selfwas 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:
to this:
Here’s a cleaned up version of the code that also eliminates global variables and unnecessary function definitions: