JavaScript setInterval() Method

The setInterval() method in JavaScript is used to execute the code after every specified time intervals.

JavaScript setInterval() Method Example

Here is an example demonstrates setInterval() method in JavaScript:

<!DOCTYPE HTML>
<html>
<head>
   <title>JavaScript setInterval() Method</title>
   <script type="text/javascript">
      function timemsg()
      {
         var si = setInterval("alert('2 seconds!')", 2000);
      }
   </script>
</head>
<body>

<h3>JavaScript setInterval() Method Example</h3>
<p>Click on the button below to show alert box after every 2 seconds.</p>
<form>
   <input type="button" value="Timed Alert Box" onClick="timemsg()">
</form>

</body>
</html>

Here is the sample output of the above setInterval() method in JavaScript example. This is the initial output:

javascript setinterval method

This is the output produced after 2 seconds, after pressing the button Timed Alert Box:

javascript setinterval method example

Here is the live demo output produced by the above setInterval() method example program in JavaScript.

Click on the button below to show alert box after every 2 seconds.

JavaScript Online Test


« Previous Tutorial Next Tutorial »