Skip to content
Related Articles

Related Articles

Improve Article

Explain clearTimeout() function in Node.js

  • Difficulty Level : Expert
  • Last Updated : 21 Sep, 2021
Geek Week

In node.js, there exists a timer module that is used to schedule timers and execute some kind of functionality in some future time period.

setTimeout() method: It is used to schedule functionality to be executed after provided milliseconds, below is a simple example of setTimeout() method.

Example: The setTimeout inside the script tag is registering a function to be executed after 3000 milliseconds and inside the function, there is only an alert.

HTML




<!DOCTYPE html>
<html>
  
<body>
    <script>
        function alertAfter3Seconds() {
            alert("Hi, 3 Second completed!");
        }
        setTimeout(alertAfter3Seconds, 3000);
    </script>
</body>
  
</html>

 



Output:

 

clearTimeout() Method: This method comes under the category of canceling timers and is used to cancel the timeout object created by setTimeout. The setTimeout() method also returns a unique timer id which is passed to clearTimeout to prevent the execution of the functionality registered by setTimeout. 

Example: Here we have stored the timer id returned by setTimeout, and later we are passing it to the clearTimeout method which immediately aborts the timer.

Javascript




<!DOCTYPE html>
<html>
  
<body>
    <script>
        function alertAfter3Seconds() {
            alert("Hi, 3 Second completed!");
        }
          
        const timerId = setTimeout(alertAfter3Seconds, 3000);
  
        clearTimeout(timerId);
        console.log("Timer has been Canceled");
    </script>
</body>
  
</html>

Output: Here we will not be able to see that alert registered to be executed after 3000 milliseconds because clearTimeout canceled that timer object before execution.

Hey geek! The constant emerging technologies in the world of web development always keeps the excitement for this subject through the roof. But before you tackle the big projects, we suggest you start by learning the basics. Kickstart your web development journey by learning JS concepts with our JavaScript Course. Now at it’s lowest price ever!




My Personal Notes arrow_drop_up
Recommended Articles
Page :