Reputation: 571
I have a live updating div on my website. It works fine however the user always have to wait 5 seconds before it loads. Heres my code:
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.7.2/jquery.min.js">
</script>
<script type="text/javascript">
$(document).ready(function() {
$.ajaxSetup({ cache: false });
setInterval(function() {
$('#div-id').load('/something.php');
}, 5000);
});
</script>
Is there a way I can load, it then wait 5 seconds and load it again? Instead of wait 5 seconds, load it, then wait again...
Thanks
Upvotes: 1
Views: 746
Reputation: 128791
Yes. jQuery's load()
method has a complete callback function as a parameter:
.load( url [, data ] [, complete ] )
complete
A callback function that is executed when the request completes.
Thanks to this we can create a recursive function which calls itself once complete (or in this case, after 5 seconds):
function loadContent(selector, path) {
$(selector).load(path, function() {
setTimeout( loadContent(selector, path), 5000 );
});
}
loadContent('#div-id', '/something.php');
What I've done here is move your content loading logic into a new function called loadContent
, which accepts a selector and a path as its parameters. This function then triggers load()
on the passed in selector, loading the passed in path. When the content has loaded a setTimeout
function kicks in to trigger our loadContent
function once again after 5000 millisecond (5 seconds).
Triggering loadContent()
to begin with will fire our function off immediately, meaning you will not have to wait 5 seconds before the content first loads.
Upvotes: 3
Reputation: 2828
Just call the load
once before
$('#div-id').load('/something.php');
setInterval(function() {
$('#div-id').load('/something.php');
}, 5000);
Upvotes: 0
Reputation: 4471
You have to run your ajax manually before first interval run.
<script type="text/javascript">
var loadContent = function() {
$('#div-id').load('/something.php');
};
$(document).ready(function() {
$.ajaxSetup({ cache: false });
loadContent();
setInterval(loadContent, 5000);
});
</script>
Upvotes: 2