Monday 3 October 2011

Using timeouts in JavaScript

Now and again it can happen that you want to time some task on your web page. For example you want to display the current time value on your site. In this case you need to update your page in every seconds. Don't worry! This task is quite simple using JavaScript. 
Before creating a complete clock we need to learn the basics of this topic. First of all there is a JavaScript function timeout() which will be used.
The timeout syntax is:  
var t = setTimeout("javascript statement",milliseconds);
Well, the first parameter is a standalone JavaScript command or it can be a function. This will be executed when the time in the second parameter was elapsed. As you can see you need to use milliseconds.
The return value is an identifier for this timer event. So if you want to cancel it you need to use this identifier.
A very simple example is the code below. Here we will display a simple alert message. We use 2 buttons here. The click on the first one will display an alert without timeout, however the click on the second button displays a message using a 3 seconds timeout.



Code:
  1. <body>
  2. <script language="javascript" type="text/javascript">
  3. <!--
  4. function delayedAlert(){
  5. setTimeout("alert('This alert was delayed');",3000);
  6. }
  7. function normalAlert(){
  8. alert('No timeout');
  9. }
  10. //-->
  11. </script>
  12. <button onclick="normalAlert();">No timeout</button>
  13. <button onclick="delayedAlert();">Delayed alert</button>
  14. </body>