Tuesday, November 19, 2024
Google search engine
HomeLanguagesJavascriptTiming Events in Javascript

Timing Events in Javascript

Timing events are the events that help to execute a piece of code at a specific time interval. These events are directly available in the HTML DOM (Document Object Model) Window object, i.e., they are present in the browser. So, these are called global methods and can be invoked through the ‘window’ object or without it. The various timing events are listed below:

setTimeout() Method: This method is used to execute a piece of code after a certain amount of time. Most of the time, this piece of code is written within a function. The function is either passed as a parameter or as an anonymous function directly as a parameter. It returns a positive integer which represents the ID of the timer created due to the call of the setTimeout method. It is optional to use a variable to store the ID but depends on the cases when we want to cancel the timer using the clearTimeout() method.

The function passed is executed after the timer stops. The parameters passed (specified after the delay time) are optional and are accessible to this function. The delay is the time for which the timer has to wait for the function execution. It is written in milliseconds, so ‘1000’ represents ‘1’ second.

Syntax:

let timeoutID = scope.setTimeout(function, delay, param1, param2, ...)

The below example demonstrates the setTimeout() method:

Example:

HTML




<!DOCTYPE html>
<html>
  
<body style="text-align:center;">
    <h1 style="color:#378E47;">
        neveropen
    </h1>
  
    <h2>setTimeout() method</h2>
    <p>Click the button and wait for 3 seconds.</p>
  
    <!-- Setting the onclick method for the button -->
    <button onclick="setTimeout(neveropen, 3000);">
        Press me
    </button>
      
    <h2 style="font-size:3em;color:#378E47;"></h2>
  
    <script>
        function neveropen() {
  
            // Fetching the first index h2 element
            var h2Heading =
                document.getElementsByTagName("h2")[1];
  
            // Changing the innerHTML tag of the
            // fetched h2 heading
            h2Heading.innerHTML = "Welcome here!";
        }
    </script>
</body>
  
</html>


Output:

clearTimeout() Method: The ‘clearTimeout()’ method is used to cancel a timeout established using the setTimeout() method. This method stops the execution of the function passed as a parameter if it is called within the time delay specified in the setTimeout() method.

It accepts a single parameter which is the timoutID that the setTimeout() method returns. An invalid ID passed to this method will not do anything.

Syntax:

scope.clearTimeout(timeoutID) 

The below example demonstrates the clearTimeout() method:

 

Example:

HTML




<!DOCTYPE html>
<html>
  
<body style="margin-left:50px;">
    <h1 style="color:#378E47;">
        neveropen!
    </h1>
  
    <h2>clearTimeout() method</h2>
    <p>Press the first button and wait 4 seconds.</p>
  
    <p>
        Press the second button before 4 seconds to
        prevent the first button to execute.
    </p>
  
    <button style="margin-right:10px" 
        onclick="startFunction()">Press me
    </button>
      
    <button onclick="stopFunction()">Stop</button>
    <h1 style="font-size:3em; color: #378E47;"></h1>
  
    <!-- Javascript Code -->
    <script>
        var setTimeoutID;
  
        function startFunction() {
            setTimeoutID = setTimeout(function () {
  
                // Fetching the first indexed h1 element
                var h2Heading =
                    document.getElementsByTagName("h1")[1];
  
                // Changing the innerHTML tag of the 
                // fetched h2 heading
                h2Heading.innerHTML = "Welcome here!";
            }, 4000);
        }
  
        function stopFunction() {
            clearTimeout(setTimeoutID);
        }
    </script>
</body>
  
</html>


Output:

setInterval() Method: This method is used to repeatedly execute a piece of code within a fixed time interval between each call. The meaning and use of each of the parameters are the same as that of the setTimeout() method. It returns a positive integer which represents the ID of the timer created due to the call of the setTimeout method. It is optional to use a variable to store the ID but depends on the cases when we want to cancel the timer using the clearInterval() method.

The parameters passed (specified after the delay time) are optional and are accessible to the function. The delay is the time that decides how often the function passed as a parameter is executed. It is written in milliseconds, so ‘1000’ represents ‘1’ second.

Syntax:

var intervalID = scope.setInterval(function, delay, param1, param2, ...)

clearInterval() Method: This method is used to cancel the repeating timed action established using the setInterval() method. This method stops the execution of the function passed as a parameter if it is called before all the intervals of the setInterval() method are over. 

It accepts a single parameter which is the intervalID that the setInterval() method returns. An invalid ID passed to this method will not do anything.

Syntax:

scope.clearInterval(intervalID)

The below example demonstrates the clearInterval() method:

Example:

HTML




<!DOCTYPE html>
<html>
  
<body style="text-align:center; color:#378E47;">
    <h1> neveropen Counter.</h1>
    <h2 style="font-size:5em;">10</h2>
  
    <!-- Setting the onclick method for the button -->
    <button onclick="neveropenCounter()">
        Press me
    </button>
  
    <!-- JavaScript code -->
    <script>
  
        // Variable for maintaining count of the timer
        let count = 10;
  
        function neveropenCounter() {
  
            // Fetching the 0th indexed h2 element
            var h2Heading =
                document.getElementsByTagName("h2")[0];
            var countDownID = setInterval(function () {
                count--;
                h2Heading.innerHTML = count;
  
                if (count <= 0) {
                    // Changing the innerHTML tag of 
                    // the fetched h2 heading.
                    h2Heading.innerHTML = "Welcome here!";
                    // Stop the timer
                    clearInterval(countDownID);
                }
            }, 1000);
        }
    </script>
</body>
  
</html>


Output:

Other Key Points:

  • The setTimeout() and setInterval() methods share the same pool for storing IDs, which means that we can use the clearTimeout() and clearInterval() methods interchangeably. However, we should avoid doing so.
  • The browsers that support the setTimeout() and setInterval() methods are mainly, Google Chrome, Internet Explorer, Safari, Opera, and Firefox.
  • When you don’t need to use the clearTimeout() or clearInterval() method, then there is no need to store the ID returned by the setTimeout() or setInterval() method respectively.
Whether you’re preparing for your first job interview or aiming to upskill in this ever-evolving tech landscape, neveropen Courses are your key to success. We provide top-quality content at affordable prices, all geared towards accelerating your growth in a time-bound manner. Join the millions we’ve already empowered, and we’re here to do the same for you. Don’t miss out – check it out now!

RELATED ARTICLES

Most Popular

Recent Comments