JavaScript: Execute a Function every Couple of Seconds with setInterval CodeUnit 14 NOV 2011

With pages being very much dynamic these days, developers often need a page to do something every now and then, so as to keep the viewer’s attention or to update the page without having to do a page reload – or perhaps just reload the page every couple of seconds!

Anyway, a simple way of achieving this is through the very useful Javascript Window setInterval() method, which basically calls a function or evaluates an expression at specified intervals (in milliseconds).

Once initiated, the setInterval() method will keep executing until the timer is cleared with a call to clearInterval() – or the window itself is actually closed!

Note the ID value returned by the call to setInterval – you’ll need this parameter if you want to put a stop to it with clearInterval!

Supported by all major browsers, the syntax to run the method is:

setInterval(code,millisec);

The following is a simple example that displays the time on a page and then subsequently updates that time every second, with a control button to stop the clock.

<html>
<body>
<input type=”text” id=”clock” />
<script language=javascript>
var int=self.setInterval(function(){clock();},1000);
function clock()
  {
  var d=new Date();
  var t=d.toLocaleTimeString();
  document.getElementById(“clock”).value=t;
  }
</script>
</form>
<button onclick=”int=window.clearInterval(int)”>Stop</button>
</body>
</html>

Nifty

Related Posts:

About Craig Lotter

Software developer, husband and dad to two little girls. Writer behind An Exploring South African. I don't have time for myself any more.