We all know sites that refresh themselves (sometimes even before we finished reading what we were reading). Usually, the types of sites that need to be refreshed are sites with pages that changes frequently like news sites.
If you ever asked yourself how they do it, then the answer is quite simple and we are here to answer it: using Javascript code.
The truth is that the easiest way to schedule page to be refreshed is actually not using Javascript, but using one script line in HTML that looks like this:
This line should be places in the section of our HTML document and it will cause the page to be refreshed every 15 seconds.Of course you can change the refresh time as needed. For example if we want the page to be refreshed every 2 minutes our code will look like this:
You are probably wondering if it's so easily done in HTML then why you should know how to schedule events in Javascript?
The answer is quite simple: because sometimes we need to change parts of our page on client side, so we don't want to cause the entire page to go all the wayto the server and back. For example suppose we want to display an on-screen clock with seconds hand which
is in constant motion. Or we want to write a presentation of images in which images are changing automatically every few seconds. In the following example will create a Javascript function that will refresh a page 5 seconds after the function is called.
You can of course call it from a link or a button or in any other way that is appropriate for you. You can also call another function from within the refreshing function.
Sample code for scheduled page refresh event:
RefreshPage function ()
{
var t = setTimeout ("refresh ()", 5000);
}
The SetTimeout function takes two values:
1) The name of the function we want our function to call.
2) The time interval for calling the function from our function
Time will always be in milliseconds, which means that every second is worth 1000 milliseconds. The called function can be one of JavaScript's built in functions or a function you wrote yourself.
This code will work also within a frame, so even if you put your page within a frame you can still use it.