Running A JavaScript Function Every So Often
Sometimes, it is desirable to run a certain JavaScript function every so often on a web page. A clock update or an image rotation are possibilities.
For a working example, let us make a function Testing():
<script type="text/javascript"><!-- function Testing() { alert("Hello !!!"); } //--></script>
Testing() simply spawns an alert box with the message, "Hello !!!".
Let's use the JavaScript setInterval() function to make Testing() run every 2 minutes.
The setInterval() function takes two parameters, the command and the interval. This makes Testing() run every 2 minutes:
setInterval( Testing, 2*60*1000 );
The first parameter is the name of the function to run (the function name without parenthesis "()" appended). The second parameter is an interval expressed in milliseconds.
The number of milliseconds could be precalculated and typed in (120000). Or, it can be done as in the example and let the browser calculate it.
In the example, the interval is expressed as 2*60*1000. The "2" is the number of minutes. The "60" is the number of seconds per minute. The "1000" is the number of milliseconds per second. The calculation yields the correct number of milliseconds for a 2-minute interval.
To see the working example, put the above JavaScript into a test web page. Then, put this JavaScript somewhere below the first:
<script type="text/javascript"><!-- setInterval( Testing, 2*60*1000 ); //--></script>
Or, if you prefer, the setInterval() function can be in the same JavaScript block as the function it affects. Like this:
<script type="text/javascript"><!-- function Testing() { alert("Hello !!!"); } setInterval( Testing, 2*60*1000 ); //--></script>
The alert box with message, "Hello !!!" will appear every 2 minutes.
Will Bontrager