JavaScript Timing Events

With JavaScript Time events the codes can be executed in time-intervals. There are four methods available to use for timing events in JavaScript which are as follows :

1. setTimeout() :

The setTimeout() method is used to create a timing events, means it executes a function after waiting a specified number or milliseconds. The syntax of setTimeOut() method is as follow :
  var time = setTimeout(function, milliseconds);
Where function is the name of function or method which you want to call in a given milliseconds of intervals. Lets see an example :
<html>
<body>
  <p>The Alert message will appear after 2 seconds of delay</p>
  <input type="button" onclick="setTimeout(sayHello, 2000)" value="Click Here"/>
  <script>
    function sayHello() {
      alert("Hello world. This is Time Interval test.");
    }
  </script>
</body>
</html>
Output :

The Alert message will appear after 2 seconds of delay

2. clearTimeout() :

The clearTimeout() method is used to stops the execution of the function specified in setTimeout(). The syntax would be :
 clearTimeout(TimerVariable);
Where the TimerVariable is the variable returned from setTimeout(). Now lets see an example :
<html>
<body>
  <p>The Alert message will appear after 4 seconds of delay</p>
  <input type="button" onclick="mytime=setTimeout(sayHello, 4000)" value="Click Here"/>
  <input type="button" onclick="clearTimeout(mytime)" value="Stop Timeout"/>
  <script>
    function sayHello() {
      alert("Hello world. This is Time Interval test.");
    }
  </script>
</body>
</html>

3. SetInterval() :

The setInterval() method is used to create a timing events as setTimeout() function but instead of execute the function only one time, it repeat the execution of the function continuously. The syntax of setInterval() method is as follows :
 var rept = setInterval(function, milliseconds);

Where function is the name of function or method which you want to call in a given milliseconds of intervals. Now at here, to stop the repetition of the execution of function we need to use the clearInterval() method.


4. clearInterval() :

The clearInterval() method stops the executions of the function specified in the setInterval() method. The syntax would be :
 clearInterval(TimerVariable);
Where the TimerVariable is the variable returned from setInterval(). Now lets see an example :
<html>
<body>
  <input type="button" onclick="mytime = setInterval(startClock, 1000);" value="Start Clock"/>
  <input type="button" onclick="clearInterval(mytime)" value="Stop Clock"/>
  <p style="font-weight:bold;font-size:20px;" id="demo"></p>
  <script>
    function startClock() {
      var d = new Date();
      document.getElementById("demo").innerHTML = d.toLocaleTimeString();
    }
  </script>
</body>
</html>
Output :




Next Topic :