• 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 / setTimeout javascript – How the setTimeout() Method in JavaScript Works

setTimeout javascript – How the setTimeout() Method in JavaScript Works

September 6, 2022 Leave a Comment

The setTimeout() method in JavaScript will run a function or code after a set amount of milliseconds have passed.

setTimeout(function(){
  //Code that will run after 5000 milliseconds
}, 5000);

You can see in the code above that the setTimeout() method has the second parameter of 5000. This is how long (in milliseconds) the method will wait until running the function in the first parameter. In this case, it is 5000 milliseconds or 5 seconds.


Let’s say we want to run code that executes an alert box after 5 seconds. We can do this easily using the setTimeout method.

Here is the JavaScript code that can make this happen.

setTimeout(function(){
  alert("5 seconds have passed.")
}, 5000);

Let’s take a look at another example below.

Creating a Countdown Timer Using the setTimeout() Method

In this example, we will use the setTimeout() method to create a simple countdown timer that will display a message when finished. It will start when the user presses a button.

Here is the simple HTML setup:

<div id="div1">
  <div id="click-me" onclick="startCountdown()">Start 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 JavaScript to wait 5 seconds using the setTimeout() method. While we are waiting for the 5 seconds, 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 starting at 5 seconds. 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.

Finally, in our setTimeout() method, once the 5 seconds is up, we will have an alert box alert the user that the timer is done. We will also add some code to make it so the user can’t run the countdown timer 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;
  
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;
    
    setTimeout(function(){
      isSetTimmeoutRunning = false;
      //Send alert message to the user
      alert("5 seconds have passed.");
    }, 5000);
    
    //The initial starting point of the counter, 5
    var counter = 5;
    
    document.getElementById("countdown-text").innerHTML = "<b>" + counter + "</b>";

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

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

Code Output:

Start Countdown

Full Code:

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

<script>

var isSetTimmeoutRunning = false;  
function startCountdown(){
  if( isSetTimmeoutRunning == false ){
    isSetTimmeoutRunning = true;
    setTimeout(function(){
      isSetTimmeoutRunning = false;
      alert("5 seconds have passed.");
    }, 5000);
    var counter = 5;
    document.getElementById("countdown-text").innerHTML = "<b>" + counter + "</b>";
    var interval = setInterval(function(){
      counter--;
      document.getElementById("countdown-text").innerHTML = "<b>" + counter + "</b>";
      if( counter == 0 ){
        document.getElementById("countdown-text").innerHTML = "";
        clearInterval(interval);
      }
    }, 1000);
  }
}

</script>

Hopefully this article has been useful for you to understand how setTimeout() in JavaScript works.

Other Articles You'll Also Like:

  • 1.  JavaScript tan – Find Tangent of Number in Radians Using Math.tan()
  • 2.  Using JavaScript to Reverse an Array
  • 3.  How to Empty a String in JavaScript
  • 4.  JavaScript sinh – Find Hyperbolic Sine of Number Using Math.sinh()
  • 5.  JavaScript String startsWith Method
  • 6.  Using JavaScript to Check If String Contains Only Certain Characters
  • 7.  How to Use JavaScript to Change Button Text
  • 8.  Using JavaScript to Remove the Last Character From a String
  • 9.  Push Multiple Items to Array in JavaScript
  • 10.  Using JavaScript to Remove Leading Zeros

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