Advertisements

Archive

Posts Tagged ‘Examples of setTimeout() with Javascript’

How to refresh page using javascript freaquently and automatically ?

July 25, 2011 2 comments

Refresh web page using javascript with regular intervals

In some scenario, we need to refresh our web page automatically with some interval of time. The better method to do it is using Javascript function. Then we can set a time interval period and for each interval time page will be refresh without any user interaction with web page.

Using setTimeout() with Javascript

The Javascript setTimeout() function allows code to be executed a set of time after some trigger, such as when the page has loaded or a button is pressed.  That means, the setTimeout() method calls a function or evaluates an expression after a specified number of milliseconds.

Syntax of SetTimeOut() in Javascript

setTimeout(code,millisec,lang)

Examples of setTimeout() with Javascript

A simple example of setTimeout() in javascript, below sample function shows alert message with the time interval 3 seconds after click the button.

<html>
<head>
<script type="text/javascript">
function timedMsg()
{
var t=setTimeout("alert('I am displayed after 3 seconds!')",3000)
}
</script>
</head>
<body>

<form>
<input type="button" value="Display timed alertbox!" onclick="timedMsg()" />
</form>

</body>
</html>
 

Below mentioned example of setTimeout() in Jvascript will start count down after click the button up to the seconds that we enterd into the text box. It is very simple sample for setTimout(0 in javasscript can be easily understood by beginners also.

 

<html>
<head>
<script type="text/javascript">
var c=0;
var t;
var timer_is_on=0;

function timedCount()
{
document.getElementById('txt').value=c;
c=c+1;
t=setTimeout("timedCount()",1000);
}

function doTimer()
{
if (!timer_is_on)
  {
  timer_is_on=1;
  timedCount();
  }
}
</script>
</head>
 

How to reload web page frequently and automatically using javascript setTimeout() function? Below mentioned function will help to refresh page frequently with the time of interval that we mentioned.  We can done it by two methods

  1. In meta tage we can set time of interval and have to also mention url that we have to load with the time of interval.
<meta http-equiv="refresh" content="30;url=index.html">
  1. 2.  Next option is create a method in javascript and call it in page load as mentioned below.  
<script type="text/javascript">
    window.onload = setupRefresh;

    function setupRefresh() {
      setTimeout("refreshPage();", 30000); // milliseconds
    }
    function refreshPage() {
       window.location = location.href;
    }
  </script>
Advertisements
%d bloggers like this: