Page 1 of 1

JS repeating and repeating again.

Posted: Wed Feb 20, 2013 4:25 am
by overras
Hello indie developers. I came here with a problem what is over my knowledges . Well, I use this code to take data in real time from database.

Code: Select all

var timeout = false;

function getData()
{
	
	  $.ajax({
                type: "POST",
                url: "modules/external_scripts/data_realtime_loading/loading.php",
			   success:function(data) {

	   		 var divs = $(data).filter(function(){ return $(this).is('div') });
divs.each(function() {

	 $("#"+$(this).attr('id')+"").html($(this).html());
});
			   }
			 
	});
	timeout = setTimeout('getData()', 5000);
}
And this function to load any page of the website ex: blacksmith ( index.php?pag=village&sub=blacksmith ) .

Code: Select all

function load(link) {
		$('#website').load(link);
}
index.php - is the game theme. With pag= and sub= I load the pages in a content called "content" . Well, the problem is, with every click on a link who call the "load" function, the getData() function is repeating and repeating again, like a rewrite until the page is refreshed, and how I think you know aleardy, one player can overload the server just spamming a link. Example, if I click on a link with that function , in firebug I recieve 5-6 callbacks at once, normally 1 at 5 seconds, but after spam, 5-6 per 1-2-3 seconds.

<a class="link" onClick="load('?pag=options&sub=options_interface')">Options</a>

Please gentlemens, any advice or a way to fix that?

Re: JS repeating and repeating again.

Posted: Wed Feb 20, 2013 5:59 am
by Jackolantern
Try putting a clearTimeout(timeout); call in your function before you set it again. Since you declared it outside of the function, you should be keeping a valid reference to it, so I don't think it is getting lost, creating new timeouts and then they are all ticking away, but Javascript is weird sometimes. The setTimout() is the only likely culprit I can see that could be causing the page to continuously refresh at a faster and faster pace as the button is clicked.

Re: JS repeating and repeating again.

Posted: Wed Feb 20, 2013 1:33 pm
by overras
Thank you very much Jack! It really works! For who will have this problem in the future:

Code: Select all

var timeout = false;

function getData()	{
	clearTimeout(timeout);
	  $.ajax({
                type: "POST",
                url: "modules/external_scripts/data_realtime_loading/loading.php",
			   success:function(data) {

	   		 var divs = $(data).filter(function(){ return $(this).is('div') });
divs.each(function() {

	 $("#"+$(this).attr('id')+"").html($(this).html());
});
			   }
			 
	});
	timeout = setTimeout('getData()', 5000);
}

Re: JS repeating and repeating again.

Posted: Thu Feb 21, 2013 12:24 am
by Jackolantern
Awesome! Glad it works :)