The Netlobo logo - a Nevada desert landscape

Javascript location.reload example

An example of how to use Javascript's location.reload function

Published Aug 5, 2005 by lobo235

Many web pages on the internet are dynamically generated using PHP or some other scripting language. Dynamically generated pages can provide the website's visitors with up to the minute information that static pages cannot. There are some pages that visitors refresh often because of the data they contain. For example, pages with stock quotes, news, auctions, statistics, sports scores, and bank accounts all have data that can be changed at any second. The Javascript location.reload function gives your visitors an easier way to reload the page.

There are a few different ways to implement the location.reload function. You can provide a simple link that the user can click on to call the Javascript function or you can use a timer that calls the location.reload function at a specified interval.

Here is an example of how to use Javascript's location.reload in a link:

<a href="javascript:location.reload();">Refresh the page</a>

The above HTML is pretty simple and easy to understand. When the user clicks the link the page will reload or we could say, refresh. It basically does the same thing as the user's refresh button in their browser but they don't have to drag their mouse pointer all the way up to the refresh button, instead they just use your "Refresh the page" link.

The other method of using location.reload which involves a timer is a little more complex. You will need to place the following code in the <head> section of your webpage or in an external Javascript file.

<script type="text/javascript" language="javascript">
var reloadTimer = null;
window.onload = function()
{
    setReloadTime(5); // In this example we'll use 5 seconds.
}
function setReloadTime(secs)
{
    if (arguments.length == 1) {
        if (reloadTimer) clearTimeout(reloadTimer);
        reloadTimer = setTimeout("setReloadTime()", Math.ceil(parseFloat(secs) * 1000));
    }
    else {
        location.reload();
    }
}
</script>
 

So when the page gets loaded, a timer is set for five seconds in this example. After five seconds the location.reload function is called and the page will reload. You can change the five to whatever you want to make the delay as long or as short as possible.

I hope this information will be of use to you. Please let me know if you have any feedback regarding this article about Javascript's location.reload function.

9 comments for this article.

del.icio.us logo add this article to del.icio.us! Other great Web Development and Programming articles on Netlobo.com:
How to test your PHP scripts
Preventing MySQL Injection attacks with PHP
Unobtrusive Javascript made easy