JavaScript's Window object comes with four methods that you can use to create timed or looping events in your Web pages. In this article, I'll introduce you to them, and also show you a few examples of how they can be used in different situations.
Here's another example, this one containing two timers. The first one is set to close the window after 30 seconds. However, 10 seconds in, the second one will activate and ask the user to confirm the timeout. If the user does not confirm it, the timeout will be cancelled.
<script language="JavaScript"> // set timeout for window to close var win = setTimeout('window.close()', 30000); // set timeout for user input var check = setTimeout('checkStatus()', 10000); // ask if user wants window to close // if no, clear timeout for window to close function checkStatus() { if(!window.confirm("This window will shut in 20 seconds. Is that OK?")) { window.clearTimeout(win); } } </script>
Note that after the confirm() dialog bog is displayed and while it is waiting for a user click, all timers are suspended.
Here's another example, this one using the setTimeout() method to create a countdown clock. Take a look:
<html> <head> <script language="JavaScript"> var i=10; function countDown() { if(i > 0) { document.forms[0].elements[0].value=i; i = i-1; var c = window.setTimeout("countDown()", 1000); } else { alert("Happy New Year!"); } } </script> </head> <body onLoad="countDown()"> <form> <input type="text" name="counter" size="3"> </form> </body> </html>
In this case, I'm using the setTimeout() method to call itself in a loop every second, and updating the value of the countdown clock on every iteration of the loop. When the countdown hits 0, an alert box is displayed.