JAVA SCRIPT - Using a Timer to Automatically Update the Page with Fresh Data

Using a Timer to Automatically Update the Page with Fresh Data


You want to display entries from a file, but the file is updated frequently. 


Use Ajax and a timer to periodically check the file for new values and update the display accordingly. The Ajax we use is no different than any other Ajax request. We’ll use a GET, because we’re retrieving data.

 We put together the request, attach a function to the onreadysta techange event handler, and send the request: 

var xmlhttp;
// prepare and send XHR request
function populateList() {
 var url = 'text.txt'; // change to full url to prevent caching problems'GET', url, true);
 xmlhttp.onreadystatechange = processResponse;

In the code that processes the response, we just place the new text into a new unordered list item and append it to an existing ul element:

// process return
function processResponse() {
 if(xmlhttp.readyState == 4 && xmlhttp.status == 200) {
 var li = document.createElement("li");
 var txt = document.createTextNode(xmlhttp.responseText);
 } else if (xmlhttp.readyState == 4 && xmlhttp.status != 200) {

The new part is the addition of the setTimeout() in the code. It triggers the entire process again in 15 seconds.The process is started by creating the xmlHttpRequest object in the Window load event handler, and then calling populateList() the first time:

window.onload=function() {
 xmlhttp = new XMLHttpRequest();


The fact that we’re doing a direct request on a static text file might be new, but remember that a GET request is more or less the same as the requests we put into the location bar of our browsers. If something works in the browser, it should successfully return in an Ajax GET request…within reason. 

The key to using timers with Ajax calls is to make sure that the last call is completed before making the next. By adding the call to setTimeout() at the end of the Ajax call, we trigger the timer when we know an outstanding request isn’t being processed. We can also put in a check for the request status, and cancel the timer event altogether if we’re concerned about hitting a failing service, over and over again. When I ran the application that included the solution code, 

I changed the text file by using the Unix echo command: 

$ echo "This is working" > text.txt


Post a Comment