/  Technology   /  SetInterval() & setTimeout() Methods
j1

SetInterval() & setTimeout() Methods

 

JavaScript usually executes in  synchronous manner. However, there are several built-in JavaScript functions that allow us to delay the execution of instructions.

The setTimeout() and setInterval() functions let you run  JavaScript functions at a specific time. In this article, we’ll examine the operation of these two approaches and look at some real-time examples.

The setTimeout() method calls a function after a number of milliseconds. It executes the function after the time allotted has been completed.

setTimeout().html

<!DOCTYPE html>
<html>
    <title>setTimeout()</title>
   <body>
      <p>Click on the button, then wait 4 seconds and the page will alert "Example of setTimeout()".</p>
      <p>Click the "Stop" button before the 4 seconds have elapsed.</p>
      <button onclick="timerId = setTimeout(sayHello, 4000);">Click here</button>
      <button onclick="clearTimeout(timerId)">Stop</button>
      <script>
         function sayHello() {
           alert( 'Example of setTimeout()' );
         }
      </script>
   </body>
</html> 

setTimeout() :

j2

The setInterval() method calls a function at specified intervals (in milliseconds).

The setInterval() method continues calling the function until clearInterval() is called, or the window is closed.

setInterval().html

<html>
    <title>setInterval()</title>
   <body>
      <p>Click on the buttons, to start / stop the counter.</p>
      <button onclick="timerId = setInterval('counter()', 2000);">Start</button>
      <button onclick="clearInterval(timerId)">Stop</button>
      <br><br>
      <div id="1"> </div>
      <script>
         var i = 0;
         function counter(){
            i = i + 1;
/html>
            document.getElementById('1').innerHTML += i + "<br>";
         }
      </script>
</body>
<

setInterval() :

j3 

 

Leave a comment