There can be multiple scenarios where a programmer decides to execute a function at a later time, instead of running it instantaneously. This kind of behavior is "scheduling as call" or "scheduling a timeout". In this article, we will cover the JavaScript Timeout. Let's look at the list of topics which we are going to cover in this article:-

  • What is Timeout in JavaScript?
    • How to Schedule a Timeout in JavaScript using setTimeout and setInterval?
    • How to clear the Scheduled Timeout using clearTimeout and cleanInterval?

What is Timeout in JavaScript?

I'm sure almost every programmer would have faced the following scenarios during their development career:

  • A specific function developed need to wait for some time before performing a particular task or triggering an event.
  • A specific function or task needs to repeat at a predefined interval.

Now, to handle all such kind of scenarios, JavaScript provides the "Timeout" functionality. Moreover, this functionality essentially allows the JavaScript developer to specify in a script that a particular function or piece of JavaScript code should execute after a specified interval of time has elapsed or should be repeated at a set interval time only.

Let's discuss in the next section, how to achieve both of these tasks using the features provided by JavaScript.

How to schedule a Timeout in JavaScript?

JavaScript provides two methods to achieve the scheduling functionality. These are:

  • setTimeout()
  • setInterval()

Let's discuss both of these functions in detail:

setTimeout()

This function allows us to run a function once after the specified interval of time. Additionally, its syntax looks like below:

Syntax:

let timerId = setTimeout(function, timeInMilliseconds, param1, param2, ...);

Where,

  • functionThis parameter specifies the function that needs to execute. Additionally, it is a mandatory parameter.
  • timeInMilliseconds: The parameter specifies the "number of milliseconds" to wait before executing the code. If omitted, we use the value 0. Additionally, it is an optional parameter.
  • param1, param2, ... : These are the additional parameters to pass to the function. Moreover, these are the optional parameters.

Let's understand the usage of setTimeout() function with few examples for some sample scenarios:

Example 1: Wait for Alert
Now, consider a straightforward situation, that the user needs to display an alert after 2 seconds. One can achieve this with the help of setTimeout() as shown in the below code snippet:

<html>

   <body>  

      Demonstrating setTimeout in javascript

   </br>

      <script type = "text/javascript">

        setTimeout(()=>{

            alert("Tools QA");

        },2000)

      </script>   

   </body>

</html>

Save the file with name setTimeoutForAlert.html. After that, open it in any browser (Chrome, Firefox, or IE). It should show the output as:

 setTimeout in javascript For Alert

It is evident from the above code and snapshot that the browser will display the alert with "Tools QA" as text after 2 seconds of the page load.

setInterval()

This method allows us to run a function repeatedly, starting after the interval of time and then repeating continuously at that interval. Additionally, its syntax looks like below:

Syntax:

let timerId = setInterval(function, timeInMilliseconds, param1, param2, ...)

Where,

  • functionThis parameter specifies the function that needs to execute. Additionally, it is a mandatory parameter.

  • timeInMilliseconds: The parameter specifies the intervals (in milliseconds) on how often to execute the code. If the value is less than 10, we use the value 10. Also, it is an optional parameter.

  • param1, param2, ... : These are the additional parameters to pass to the function. Moreover, these are the optional parameters.

Let's understand the usage of setInterval() function with the following example:

Example: Display a digital clock

Let's modify the above scenario of displaying a digital clock using the setInterval() method as shown in the below code snippet:

<html>
  <body>
    Demonstrating setInterval for displaying a clock in javascript:
  
    <p id="txt"></p>

    <script>
      var myVar = setInterval(myTimer, 1000);

      function myTimer() {
        var date = new Date();
        var time = date.toLocaleTimeString();
        document.getElementById("txt").innerHTML = time;
      }
    </script>

  </body>
</html>

Save the file with name setIntervalForClock.html and open it in any browser (Chrome, Firefox, or IE). It should show the output as:

 setInterval for Digital clock

As is evident from the above code snippet and snapshot, it displays the digital time that gets updated every second using the setInterval() method.

How to clear the Scheduled Timeout?

To cancel the scheduled tasks, JavaScript provides two methods:

  • clearTimeout()
  • clearInterval()

clearTimeout()

This method clears a timer set with the setTimeout() method and prevents the function set with the setTimeout() to execute. Additionally, its syntax looks like below:

Syntax:

clearTimeout(timerId_of_setTimeout)

Where,

  • timerId_of_setTimeout: This parameter is the ID value of the timer returned by the setTimeout() method. Moreover, it is a mandatory field.

  • Let's understand the functionality of clearTimeout() in detail with the help of following code snippet:

<html>
	<body>

		<button onclick="startCount()">Start count!</button>
		<input type="text" id="txt">
		<button onclick="stopCount()">Stop count!</button>

		<p>
			Click on the "Start count!" button above to start the timer 
			</br> Click on the "Stop count!" button to stop the counting.
		</p>

		<script>
			var count = 0;
			var time;
			var timer_flag = 0;

			function timedCount() {
	  			document.getElementById("txt").value = count;
	  			count = count + 1;
	  			time = setTimeout(timedCount, 1000);
			}

			function startCount() {
	  			if (!timer_flag) {
	    			timer_flag = 1;
	    			timedCount();
	  			}
			}

			function stopCount() {
	  			clearTimeout(time);
	  			timer_flag = 0;
			}
		</script>

	</body>
</html>

Save the file with name clearTimeout.html and open it in any browser (Chrome, Firefox, or IE). It should show the output as:

 clearTimeout demo

The above gif file shows how using the clearTimeout() method. The user can prevent the function from executing, which set using the setTimeout() method.

clearInterval()

This method clears the timer set with the setInterval() method or can cancel the schedule created using the setInterval() method. Additionally, its syntax looks like below:

Syntax:

clearInterval(timerId);

Where,

timeId: The parameter signifies the timer returned by the setInterval() method. It is a required field.

Let's understand the functionality of clearInterval() in detail with the help of following code snippet, where user can invoke the clearInterval() method to stop the digital clock initiated using setInterval() method:

<html>
  <body>
    Demonstrating clearInterval for displaying/Stopping a clock in javascript:
  
    <p id="txt"></p>

    <button onclick="stopWatch()">Stop Timer</button>

    <script>
      var myVar = setInterval(myTimer, 1000);

      function myTimer() {
        var date = new Date();
        var time = date.toLocaleTimeString();
        document.getElementById("txt").innerHTML = time;
      }

      function stopWatch() {
        clearInterval(myVar);
      }
    </script>

  </body>
</html>

Save the file with name clearInterval.html and open it in any browser (Chrome, Firefox, or IE). It should show the output as:

 clearInterval demo

In the above example, as soon as one clicks the Stop Timer button, the setInterval function terminates.

Key Takeaways

  • Firstly, if you want to schedule the execution of a task/function, the same can be achieved in JavaScript using the setTimeout() and setInterval() methods.
  • Secondly, if you want to cancel the already scheduled tasks, the same can be achieved in JavaScript using the clearTimeout() and clearInterval() method.

To conclude, let's now move to the next article, where we will understand the concepts of "Promises in JavaScript".

JavaScript Objects
JavaScript Objects
Previous Article
Promises in JavaScript
Promises in JavaScript
Next Article
Arunkumar Chandra
Test USer
Reviewers
Ravinder Singh's Photo
Ravinder Singh

Similar Articles

Feedback