/  Technology   /  SetInterval() & setTimeout() Methods

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.


<!DOCTYPE html>
      <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>
         function sayHello() {
           alert( 'Example of setTimeout()' );

setTimeout() :


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.


      <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>
      <div id="1"> </div>
         var i = 0;
         function counter(){
            i = i + 1;
            document.getElementById('1').innerHTML += i + "<br>";

setInterval() :



Leave a comment