Reputation: 125
I want to reload a div
every 5 seconds. For this I found a script online which works. The only issue is that the first load of the file is after 5 seconds, but I want to first one to be immediately. It's probably a minor thing but I have never worked with Javascript before. Thank you!
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js"></script>
<script>
function autoRefresh_div() {
$("#div").load("load.html");
}
setInterval('autoRefresh_div()', 5000);
</script>
Upvotes: 7
Views: 15686
Reputation: 93
immediately invoke the expression
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js"></script>
<script>
function autoRefresh_div() {
$("#div").load("load.html");
}
autoRefresh_div();
setInterval(autoRefresh_div(), 5000);
</script>
Upvotes: 1
Reputation: 337550
You need to setup the interval timer and then call the function directly. Try this:
function autoRefresh_div() {
$("#div").load("load.html");
}
setInterval(autoRefresh_div, 5000); // every 5 seconds
autoRefresh_div(); // on load
Also note that it's better practice to chain the requests using setTimeout()
, rather than queue them. This is because if the server slows, or gets bogged down in requests you won't keep piling them on, as the next request only fires after the previous one completes. Try this:
function autoRefresh_div() {
$("#div").load("load.html", function() {
setTimeout(autoRefresh_div, 5000);
});
}
autoRefresh_div();
Upvotes: 8