JavaScript – How to Schedule a Timeout ?

Hello Readers, CoolMonkTechie heartily welcomes you in this article.

In this article, we will learn about JavaScript Timeout Concept. 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 called “scheduling as call or “scheduling a timeout”.

For better understanding about the timeout concepts, We will discuss the below following 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?
  • How to clear the Scheduled Timeout in JavaScript?

A famous quote about learning is :

” Tell me and I forget, teach me and I may remember, involve me and I learn.”

So, Let’s begin.

What is Timeout in JavaScript?

We are sure that 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.

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:

1. 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, <em>param1, param2, ...</em>);

Where,

  • function: This 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("WelCome!!");

        },2000)

      </script>   

   </body>

</html>

It is evident from the above code that the browser will display the alert with “WelCome!!” as text after 2 seconds of the page load.

2. 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(<em>function, timeInMilliseconds, param1, param2, ...</em>)

Where,

  • function: This 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>
      const myLet = setInterval(myTimer, 1000);

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

  </body>
</html>

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

How to clear the Scheduled Timeout in JavaScript?

To cancel the scheduled tasks, JavaScript provides two methods:

  • clearTimeout()
  • clearInterval()

1. 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>
			let count = 0;
			let time;
			let 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>

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

2. 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>
      const myInterval = setInterval(myTimer, 1000);

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

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

  </body>
</html>

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

That’s all about in this article.

Conclusion

In this article, We understood about JavaScript Timeout Concepts. We conclude that :

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

Thanks for reading ! I hope you enjoyed and learned about JavaScript Timeout Concept. Reading is one thing, but the only way to master it is to do it yourself.

Please follow and subscribe us on this blog and and support us in any way possible. Also like and share the article with others for spread valuable knowledge.

If you have any comments, questions, or think I missed something, feel free to leave them below in the comment box.

Thanks again Reading. HAPPY READING !!???

Exit mobile version