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:


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.

<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();
<button onclick=”int=window.clearInterval(int)”>Stop</button>


Related Posts:

About Craig Lotter

South African software architect and developer at Touchwork. Husband to a cupcake baker and father to two little girls. I don't have time for myself any more.