• Skip to primary navigation
  • Skip to main content
  • Skip to primary sidebar

The Programming Expert

Solving All of Your Programming Headaches

  • HTML
  • JavaScript
  • jQuery
  • PHP
  • Python
  • SAS
  • Ruby
  • About
You are here: Home / JavaScript / Using JavaScript to Stop a Timer

Using JavaScript to Stop a Timer

September 2, 2022 Leave a Comment

The best way to use JavaScript to stop a timer we have created is by using the clearInterval() and clearTimeout() methods. The clearInterval() method in JavaScript clears the timer which has been set by a setInterval() method.

var interval = setInterval(function(){
  //Code that will run every 1000 milliseconds
  if( //some condition ){
    //This will stop the timer
    clearInterval(interval);
  }
}, 1000);

And the clearTimeout() method in JavaScript clears the timer which has been set by a setTimeout() method.

var interval = setTimeout(function(){
  //Code that will run every 1000 milliseconds
  if( //some condition ){
    //This will stop the timer
    clearTimeout(interval);
  }
}, 1000);

Creating a JavaScript Timer and Using JavaScript to Stop the Timer

In this example, we will create a simple countdown timer using JavaScript, and then we will use JavaScript to stop the timer whenever we please.

You can look at the post we have linked above to see how to create a countdown timer. We will create a countdown timer that will run for 10 seconds.

Here is the initial HTML setup:

<div id="div1">
  <div id="click-me" onclick="startCountdown()">Start Countdown</div>
  <div id="click-me" onclick="stopCountdown()">Stop Countdown</div>
  <div id="countdown-text"></div>
</div>

To make this countdown timer happen, we will use the setTimeout() method and the setInterval() method. We will use 10 seconds as the start number for the timer.

While the setTimeout() method is waiting to execute its function call, we will provide the user with a countdown by using the setInterval() method. The setInterval() method will run every second until it is told to stop.

Inside the setInterval() method, we will run a function that runs every second. The function will display how many seconds remain in the countdown timer. We will use the innerHTML property to update the text for the user.

We will end the setInverval() method using the clearInterval() method when our counter has reached 0, OR we will stop the timer by using the clearInterval() and clearTimeout() methods when the user clicks the stop timer button we have provided.

Finally, in our setTimeout() method we will have an alert box alert the user when the countdown timer is done. We will also add some code to make it so the user can’t run the countdown timer again until it has completed its cycle.

Here is the JavaScript code:

//The variable below will just make it so the user cannot run the setTimeout method more than once at a time
var isSetTimmeoutRunning = false;
var timeoutInterval;
var interval;
var timerSeconds;
  
function startCountdown(){

  if( isSetTimmeoutRunning == false ){
      //We set this variable to true when we first run the setTimeout method.
      //It will get set back to false when the setTimeout method has completed
      isSetTimmeoutRunning = true;

      //Next, we will set our countdown timer to 60 seconds, or 60000 milliseconds
      timerSeconds = 10;
      var timerMilliseconds = 10000;
    
      timeoutInterval = setTimeout(function(){
        isSetTimmeoutRunning = false;
        //Send alert message to the user
        alert("10 seconds have passed.");
      }, timerMilliseconds);
    
      document.getElementById("countdown-text").innerHTML = "<b>" + timerSeconds + "</b>";

      interval = setInterval(function(){
        timerSeconds--;
        document.getElementById("countdown-text").innerHTML = "<b>" + timerSeconds + "</b>";
        if( timerSeconds == 0 ){
          document.getElementById("countdown-text").innerHTML = "";
          clearInterval(interval);
        }
      }, 1000);
  }
};

Next we will create a simple stopCountdown() function, that will just clear the timers we set in the function above.

function stopCountdown(){
  clearInterval(interval);
  clearTimeout(timeoutInterval);
  isSetTimmeoutRunning = false;
  document.getElementById("countdown-text").innerHTML = "";
  alert("Timer stopped!");
};

The final code and output for this example of how to create and stop a JavaScript timer is below:

Code Output:

Start Countdown
Stop Countdown

Full Code:

<div id="div1">
  <div id="click-me" onclick="startCountdown()">Start Countdown</div>
  <div id="click-me" onclick="stopCountdown()">Stop Countdown</div>
  <div id="countdown-text"></div>
</div>

<script>

var isSetTimmeoutRunning = false;
var timeoutInterval;
var interval;
var timerSeconds;
  
function startCountdown(){

  if( isSetTimmeoutRunning == false ){
      isSetTimmeoutRunning = true;
      timerSeconds = 10;
      var timerMilliseconds = 10000;
    
      timeoutInterval = setTimeout(function(){
        isSetTimmeoutRunning = false;
        alert("10 seconds have passed.");
      }, timerMilliseconds);
    
      document.getElementById("countdown-text").innerHTML = "<b>" + timerSeconds + "</b>";

      interval = setInterval(function(){
        timerSeconds--;
        document.getElementById("countdown-text").innerHTML = "<b>" + timerSeconds + "</b>";
        if( timerSeconds == 0 ){
          document.getElementById("countdown-text").innerHTML = "";
          clearInterval(interval);
        }
      }, 1000);
  }
};

function stopCountdown(){
  clearInterval(interval);
  clearTimeout(timeoutInterval);
  isSetTimmeoutRunning = false;
  document.getElementById("countdown-text").innerHTML = "";
  alert("Timer stopped!");
};

</script>

Hopefully this article has been useful for you to understand to use javascript to stop a timer.

Other Articles You'll Also Like:

  • 1.  Using JavaScript to get the Last Element in Array
  • 2.  Using JavaScript to Count the Occurrences in a String
  • 3.  Using JavaScript to Add Items to Set
  • 4.  Using JavaScript to Run a Function Every 5 seconds
  • 5.  JavaScript value – Get the Value from an Input Field
  • 6.  JavaScript atan2 – Find Arctangent of the Quotient of Two Numbers
  • 7.  Using JavaScript to Convert Float to Integer
  • 8.  Remove Special Characters From String in JavaScript
  • 9.  Using JavaScript to Reverse a Number
  • 10.  Using JavaScript to Get the Current URL

About The Programming Expert

The Programming Expert is a compilation of a programmer’s findings in the world of software development, website creation, and automation of processes.

Programming allows us to create amazing applications which make our work more efficient, repeatable and accurate.

At the end of the day, we want to be able to just push a button and let the code do it’s magic.

You can read more about us on our about page.

Reader Interactions

Leave a Reply Cancel reply

Your email address will not be published. Required fields are marked *

Primary Sidebar

About The Programming Expert

the programming expert main image

Welcome to The Programming Expert. We are a group of US-based programming professionals who have helped companies build, maintain, and improve everything from simple websites to large-scale projects.

We built The Programming Expert to help you solve your programming problems with useful coding methods and functions in various programming languages.

Search

Learn Coding from Experts on Udemy

Looking to boost your skills and learn how to become a programming expert?

Check out the links below to view Udemy courses for learning to program in the following languages:

Copyright © 2023 · The Programming Expert · About · Privacy Policy