If you're wanting to add a timed event to your web page, you will find the setTimeout() function offered by Javascript to be an adequate tool. For example, after about a minute of reading this page, an alert box will pop up to say hello. This is a really simple function that adds an event timer of sorts to your page. It takes two arguments, a string of code to be executed and a delay time in milliseconds:
| setTimeout(str code_string, int millisecond_delay) |
The code string can be a call to a user defined function or a Javascript function like alert. Were you to browse the source for this tutorial, you would see the embedded setTimeout() calls alert directly. By having it execute a user defined function, you can perform more complicated code and set a new timer to create a repeated loop.
Copy and paste the code below into an empty HTML file and open it in your web browser to see a simple example of using setTimeout() to call a user defined function on page load:
<html>
<head>
<title>Javascript Test</title>
<script type="text/javascript">
function timed_func() {
alert('There we go!');
}
setTimeout('timed_func()', 5000);
</script>
<body>
Wait a few seconds and see if it works...
</body>
</html>
Remember, the timer takes millisecond values, so you must multiple the amount of seconds you want to delay by 1000 to get the proper interval!