Controlling Web page refresh

Opinion
Oct 11, 20043 mins

* Sample JavaScript code for giving the user control over Web page refresh

In this issue I have a piece of code for you. This JavaScript is useful when you have a page that needs regular refreshing but where you’d also like to offer the user the option of turning refresh on or off.

I created this code to control the display of network performance data that an application I wrote saves periodically in an HTML file. The problem I faced was that I sometimes needed to stop the refreshing to think about the contents.

You can try this online at:

https://www.gibbs.com/examples/refresh.html

Let me know if this is useful to you or if you have a better way of doing this. Here’s the code:

gibbs.com Toggleable Refresh Example

// The following variable must be set to 1; if we start with 0

// clicking on the checkbox simply forces a single refresh

var RefreshEnabled = 1;

// This variable specifies the refresh interval in milliseconds

var RefreshInterval = 5000;

// The JavaScript setTimeout method defines the function to

// be called each time the specified period elapses.

window.setTimeout(“DoRefresh()”, RefreshInterval);

function DoRefresh()

{

    if (RefreshEnabled == 1)

      {window.location = window.location.pathname+window.location.search;}

// Let’s assume this page was generated by the URL:https://www.somesite.com/demos/refresh.html?update

//

//        

//

// The property window.location.pathname will be “demos/refresh.html”

// and the property location.search will be the URL tail (the data sent

// if the page involves a GET request). Thus the location.search property

// for the URL above would be ?update. By setting the property

// window.location to the combined value of these two existing properties

// we force the given page to be loaded from the default domain

// (“www.somesite.com”) using the default access method (“http:”).

}

function ToggleRefresh()

{

    if (RefreshEnabled == 1) {RefreshEnabled = 0;}

    else { RefreshEnabled = 1; DoRefresh(); }

}

// START TEST CONTENT.

// The following code simply gives this example something to display

// remove everything from here to “END TEST CONTENT.” unless you want to

// include an updating display of local time.

DTG = new Date();

var Hours;

var Mins;

var Secs;

var Time;

Hours = DTG.getHours();

Mins = DTG.getMinutes();

Secs = DTG.getSeconds();

if (Hours >= 12) { Time = ” PM”; } else { Time = ” AM”; }

if (Hours > 12) { Hours = Hours – 12; }

if (Hours == 0) { Hours = 12; }

if (Mins

if (Secs

document.write(“Time: ” + Hours + “:”

 + Mins + “:” + Secs + ” ” + Time );

// END TEST CONTENT.

Check to autorefresh.