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:

      <body>

      <script language="javascript" type="text/javascript">

      <!--

      function delayedAlert(){

      setTimeout("alert('This alert was delayed');",3000);

      }

      function normalAlert(){
      alert('No timeout');

      }

      //-->

      </script>

      <button onclick="normalAlert();">No timeout</button>

      <button onclick="delayedAlert();">Delayed alert</button>

      </body>

As you can see here we didn’t used the return value of the timeout function. It is because in this case we only want to make a certain task only once. In case of displaying current time we need to use a recursive call.

Republished by Blog Post Promoter

Tags: , , ,

Related posts