Reputation: 31
I am experincing some weird behavior when loadin json data via ajax with an interval. The data loads fine, only after a few intervals the data scrambles and keeps running between intervals. This even causes the browser to crash
html page
<script id="source" language="javascript" type="text/javascript">
$(function ahitRate()
{
$.ajax({
cache: false,
url: 'average.php',
data: 'jsonData',
dataType: 'json',
processData: false,
success: function(data)
{
var ahr = data[0]; //get id
var hitRate = data[1]; //get name
$('#output').html("<b>id: </b>"+ahr+"<b> name: </b>"+hitRate);
setInterval(ahitRate, 5000);
}
});
});
</script>
json php code that generates random data
// Session
session_start();
// Set the JSON header
header("Content-type: text/json");
header('Cache-Control: no-cache, must-revalidate');
$y = rand(0, 100);
// Create a PHP array and echo it as JSON
$ret = array("Average", $y);
echo json_encode($ret);
?>
Any suggestions how to solve this?
Upvotes: 2
Views: 166
Reputation: 14479
OMG!
You are calling this recursively!
setInterval(ahitRate, 5000);
EDIT: simply change setInterval(...) to setTimeout(ahitRate, 5000);
Every time it executes, the old one keeps going and a new one is added, so it will use more and more memory!
$(function() {
function ahitRate()
{
$.ajax({
cache: false,
url: 'average.php',
data: 'jsonData',
dataType: 'json',
processData: false,
success: function(data)
{
var ahr = data[0]; //get id
var hitRate = data[1]; //get name
$('#output').html("<b>id: </b>"+ahr+"<b> name: </b>"+hitRate);
}
});
}
setInterval(ahitRate, 5000);
});
The only different is that I:
This will cause your "ahitRate()" function to be invoked every 5 seconds.
Upvotes: 2
Reputation: 3608
setInterval keeps firing - and each time you get a new response you start a new timer. So after five seconds the first timer fires and starts another. Then after ten seconds BOTH timers fire, and start two more.
I think you can see where this is going.
I think you're looking for the setTimeout() method, or just start your interval timer outside the success function, so it never gets called again.
Upvotes: 1