So I searched SO to help create the following request to refresh a div
at specific intervals.
$(document).ready(function() {
$("#trigger-newsfeed").load("getNewsfeed.php");
var refreshId = setInterval(function() {
$("#trigger-newsfeed").load('getNewsfeed.php');
}, 4000);
});
This works although I was wondering if this could be made more efficient by the use of Ajax (if it is not using Ajax already without me realising).
I had tried using some other Ajax code to do this which also did work, however, other solutions would wait for the interval to finish then load the data. So for example if the interval was set to 5 seconds, each time that page is visisted, a user would have to wait for 5 seconds and then it would load; so this is the only snippet I had found worked best by relaying the information first then refreshing by the interval; although I am not sure if it is the best use of jquery to do this.
I ask this because the majority of searches made online regarding div
refreshes all point to the usage of Ajax.
You can do this.
$(document).ready(function() {
var loadNewsFeed = function () {
$("#trigger-newsfeed").load('getNewsfeed.php');
};
loadNewsFeed();
var refreshId = window.setInterval(loadNewsFeed, 4000);
});
In .ready we declare a function and assign it to the variable loadNewsFeed. Then we execute the function. Then, we setup the interval to execute every 4 seconds after that.
What you have will work, but if the network connection/computer is slow or the server gets bogged down for whatever reason, the requests could start to backup, and if that happens too much, it could crash the browser.
To fix that, use a setTimeout
instead of an interval so that it will only request new data 4 seconds after it receives the response from the previous request.
function refreshNewsFeed() {
$("#trigger-newsfeed").load("getNewsfeed.php",function(){
setTimeout(refreshNewsFeed,4000);
});
}
$(document).ready(refreshNewsFeed);