Using setInterval to reload a script - it does not reload before the first amount of time has passed (i.e: waits 120000 msec before actually displaying content). Is there a better way to do this?
<script id="source" language="javascript" type="text/javascript">
setInterval( "reloading();", 120000 );
$(function () {
reloading = function(){
$.ajax({
url: 'api.php',
data: "",
dataType: 'json',
success: function(data)
{
var id = data[0];
_id = id;
var vname = data[1];
var message = data[2];
var timestamp = data[3];
var field1 = data[4];
_field1 = field1;
var val2 = parseInt(field1, 10) + 1;
_val2 = val2;
$('#output').hide().html(timestamp +message ).fadeIn("slow");
$('#username').hide().html( vname ).fadeIn("slow");
}
});
}});
</script>
1 you are declaring reloading as a global variable and accessing it without knowing if your function is ready, that's not a good idea. If by any chance your site takes more than 2 minutes to load that will never work.
If you want to queue up your re-loads to process once every 2 minutes and run the first time without waiting, you can do it like this:
$(function(){
function reloading(){
//whatever you want to process goes here
(...)
setTimeout(function(){
reloading();
}, 120000);
}
reloading();
});
this will load your code once and then wait 12 seconds to run it again, and so on...