JavaScript

JavaScript setInterval() and setTimeout() methods Explained

JavaScript is a high-level web programming language in which every statement of code is executed line by line. However, suppose you want to execute some code or function at a later stage(in the future) and not immediately. This is called scheduling a call in Javascript and can be achieved with the two built-in methods; setTimeout() and setInterval().

This post discusses what setInterval() and setTimeout() built-in methods are in JavaScript. However, before we go any further it should be noted that these two methods are not part of JavaScript specification and are part of HTML standard specification but are supported in all the major browsers.

What is the setTimeout() Method?

The setTimeout() method is used to run a specific code in the future and not immediately by calling a callback function after a specific time interval. The callback function is defined as the function provided to another function as an argument and executed in the outer function later.

Syntax of setTimeout() Method

The syntax of setTimeout() is given below:

setTimeout(callbackFunc, milliseconds);

The first argument that we give to the setTimeout() method is the callback function which is executed after the provided milliseconds.

Example
Let us go through an example where we will set the setTimeout() method on a button and when the user clicks that button, the callback functions will be executed after 2 seconds:

<!DOCTYPE html>
<html lang="en">
<head>
  <title>setTimeout()</title>
</head>
<body>
  <!-- Initialize a button with the setTimeout method -->
  <button onclick="setTimeout(myFunction, 3000)">Try it</button>
<!-- JavaScript code inside the script tag -->
  <script>
  function myFunction() {
    alert('Hello');
  }
  </script>
</body>
</html>

In the callback function, we initialized an alert that will show after two seconds with the message hello.

What is the setInterval() Method?

The setInterval() method is the same as setTimeout() as it also executes a callback function after a specific time but with the exception that it executes the callback function continuously after that specific interval of time.

Syntax of setInterval() Method

The syntax of the setInterval() method is as follows:

setInterval(myfunc, milliseconds);

Like setTimeout() the first argument is the callback function which will be executed after the specified number of milliseconds and the execution will be repeated continuously after this specific time.

Example
Let us go through an example where we will show the current system time after every 1 second.

const myFunc=()=> {
    const d = new Date();
    console.log(d.toLocaleTimeString());
}

setInterval(myFunc, 1000);

In the above code, we first created a function in which we created a new date using the Date object and console logged the system time.

After defining the function, we used the setInterval() method, passed the function name, and 1000 milliseconds which is 1 second. Now the function will run after every 1 second and we will see our system time on the console log after every second:

Execution stoppage of setTimeout() and setInterval()

If you don’t want the callback function of setInterval() or setTimeout() to execute anymore, we can use the stopping methods available in JavaScript for both of them.

clearTimeout() Method
To stop the execution of the setTimeout() function we can use the clearTimeout() method which will take a variable/id that is returned from the setTimeout() method as an argument.

Example
In this example, we will stop the execution of the call back function defined with the setTimeout() method:

<!DOCTYPE html>
<html>

<head>
  <title>clearTimeout()</title>
</head>

<body>

  <!-- Initialize a button with the setTimeout method -->
  <button onclick="myFunc()">Try it</button>
  <button onclick="stop()">Stop</button>
  <!-- JavaScript code inside the script tag -->
  <script>
    var t;
    // function to invoke setTimeout()
    function myFunc() {
      t=setTimeout(myFunction, 3000);
    }
    // function that will be invoked after 3 seconds
    function myFunction(){
      alert("Hello");
    }
    // function for stopping the setTimeout()
    function stop() {
      clearTimeout(t);
    }
  </script>
</body>

</html>

The above code shown is an extended form of the setTimeout() example shown previously. In this code, we added another button with the name of Stop and invoked the stop() function whenever a user clicks the stop button. The stop() function has clearTimeout() that has a variable t as argument. The variable t is simply an id returned from the setTimeout() function.

When a user clicks on the Try it button then after three seconds we see Hello in the alert as seen previously. However, if the user now clicks the stop button before 3 seconds then the call back function myFunction will not be invoked and hence we won’t see an alert. This phenomenon is shown below:

clearInterval() Method
Similarly, to stop the execution of the setInterval() function, we can use the clearInterval() method that will also take the variable returned from the setInterval() as an argument.

Example

Let us go through an example where we will stop the execution of the callback function of the setInterval() method.

<!DOCTYPE html>
<html lang="en">
<head>
  <title>Document</title>
</head>
<body>
<button onclick="clearInterval(myVariable)">Stop time</button>

  <script>
  var myVariable = setInterval(myFunc, 1000);
  function myFunc() {
    const d = new Date();
    console.log(d.toLocaleTimeString());
  }
  </script>
</body>
</html>

In the above code, we defined a button in the HTML and then initialized the onclick event on this button. When the user clicks on the defined button, the setInterval() method will stop executing.

When we clicked on the “Stop time” button, the system time stopped displaying on our console log:

Conclusion

The setTimeout() and setInterval() methods both schedule a call that is to execute a function later after a specified number of milliseconds with the exception that setInterval() executes a function continuously after that specific time, unlike setTimeout() method which executes a function only once after the specified time.

In this post, we discussed what the setTimeout() and setInterval() method is and we saw their examples along with screenshots of the output. In the end, we also saw how to stop the execution of the callback functions associated with setTimeout() and setInterval() methods.

About the author

Shehroz Azam

A Javascript Developer & Linux enthusiast with 4 years of industrial experience and proven know-how to combine creative and usability viewpoints resulting in world-class web applications. I have experience working with Vue, React & Node.js & currently working on article writing and video creation.