In JavaScript, we can make a countdown timer somewhat easily with the help of the setTimeout and setInterval methods.
setTimeout(function(){
//Code that will run after 5000 milliseconds
}, 5000);
setInterval(function(){
//Code that will run every 1000 milliseconds
}, 1000);
You can see in the code above that the setTimeout() method will run the function after 5000 milliseconds. We can change that parameter to be however long we want to wait to execute the function call.
On the other hand, the setInterval() method will run the function every 1000 milliseconds. We can change that parameter to be however often we want to execute the function call.
Let’s say we want to run code that executes an alert box after 10 seconds. We can do this easily using the setTimeout method.
Here is the JavaScript code that can make this happen.
setTimeout(function(){
alert("10 seconds have passed.")
}, 10000);
Let’s take a look at another example below.
Creating a JavaScript Countdown Timer Using the setTimeout() and setInterval() Methods
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. We will also let the user enter the number of seconds they want the countdown timer to run for.
Here is the simple HTML setup:
<div id="div1">
<p>How many seconds would you like the countdown timer to start from?</p>
<input id="userInput" type="number">
<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 first get the number of seconds the user has entered into the input field using the value property. We will use this as our start number for the timer.
Once we have the seconds the user has given us, we will multiply that number by 1000 to convert it to milliseconds. We will then use that as our milliseconds parameter for the setTimeout() method.
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.
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;
function startCountdown(){
if( isSetTimmeoutRunning == false ){
//Get the seconds the user has given us and convert number to an Integer
var userInput = parseInt(document.getElementById("userInput").value);
//Make sure the user has entered a number greater than 0
if( userInput >=1 ){
//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 convert the seconds to milliseconds
var userMilliseconds = userInput*1000;
setTimeout(function(){
isSetTimmeoutRunning = false;
//Send alert message to the user
alert(userInput + " seconds have passed.");
}, userMilliseconds);
//The initial starting point of the counter is the user inputted seconds
var counter = userInput;
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 JavaScript countdown timer is below:
Code Output:
How many seconds would you like the countdown timer to start from?
Full Code:
<div id="div1">
<p>How many seconds would you like the countdown timer to start from?</p>
<input id="userInput" type="number">
<div id="click-me" onclick="startCountdown()">Start Countdown</div>
<div id="countdown-text"></div>
</div>
<script>
var isSetTimmeoutRunning = false;
function startCountdown(){
if( isSetTimmeoutRunning == false ){
var userInput = parseInt(document.getElementById("userInput").value);
if( userInput >=1 ){
isSetTimmeoutRunning = true;
var userMilliseconds = userInput*1000;
setTimeout(function(){
isSetTimmeoutRunning = false;
alert(userInput + " seconds have passed.");
}, userMilliseconds);
var counter = userInput;
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 to create a JavaScript countdown timer.
cool code helped me in creating a timer for a game I’m building only bug is it allows the input of zero and negative numbers and then it won’t stop counting down
Thanks for the comment! So we can add a simple if statement to our code to not allow users to enter a number less than 1.
if( userInput >= 1 ) {
//run the rest of our code
} else {
//Do nothing or send them a message to enter a positive number
}
I also noticed that if the user enters a decimal number it causes the same bug, so we can just use the parseInt() method to make sure this never happens.
I have updated the code above in this example to cover these two issues.
My professor wanted me to do this:
” It is your duty to create the launch sequence for takeoff. To do this, you will need to create a javascript program that counts from 50 to 0 and then sends an alert that says “Blastoff!”
He wanted us to use this code: setTimeout(function(){//fill in here; }, 5000);
I used this:
setTimeout(function(){
alert(“50 seconds have passed.”)
}, 5000);
He said we must first set the current time to 50 and decrement it by 5 seconds every time the setTimeout function activates so we would use it (the thing I said I used earlier) 10 times just by repeating it.
This is what he said:
You will need to create the variable currTime and initialize it to 50.
Then use this function.
After this function, you will decrement currTime by 1 or 5.
Then you will repeat this 10 times (cut and paste). Later we’ll use loops so you don’t have to cut and paste.
After doing this 10 times, you will have an alert that says Blastoff!
This is what I did for this portion of the assignment to do what he asked:
let, currTime=50,
setTimeout(function(){
alert(“45 seconds left”)
}, 5000);//50-5=45
setTimeout(function(){
alert(“40 seconds left”)
}, 5000);//45-5=40
setTimeout(function(){
alert(“35 seconds left”)
}, 5000);//40-5=35
setTimeout(function(){
alert(“30 seconds left”)
}, 5000);//35-5=30
setTimeout(function(){
alert(“25 seconds left”)
}, 5000);//30-5=25
setTimeout(function(){
alert(“20 seconds left”)
}, 5000);//25-5=20
setTimeout(function(){
alert(“15 seconds left”)
}, 5000);//20-5=15
setTimeout(function(){
alert(“10 seconds left”)
}, 5000);//15-5=10
setTimeout(function(){
alert(“5 seconds left”)
}, 5000);//10-5=5
setTimeout(function(){
alert(“BLAST OFF!!!”)
}, 5000);//5-5=0
The thing is though, nothing happened. What did I do wrong?
So your code is fine for the most part, just a couple of problems.
1) When I went to run your code, I got the error “Uncaught SyntaxError: Invalid or unexpected token”. This was dude to the fact that the quotations you used were likely made in a word processor. This is a good video on the issue. https://www.youtube.com/watch?v=JXE_03rXbtA
So once I changed your quotation marks from the word processor ones, “, to regular ones in a code editor,
"
, that error was fixed.That is the main reason your code did not run. However, there is one more issue.
2)Let’s take a look at the first two setTimeout methods of your code (with proper quotations added).
setTimeout(function(){
alert(
"
45 seconds left"
)}, 5000); //50-5=45
setTimeout(function(){
alert(
"
40 seconds left"
)}, 5000); //45-5=40
So one thing to remember about the setTimeout() method is that each method is independent of the other methods. So in your code above, you have two setTimeout methods that will each run after 5 seconds. So after 5 seconds, the alerts “45 seconds left” and “40 seconds left” will both run. This is not what you want though. You want “40 seconds left” to run after 10 SECONDS.
So a simple solution, you just need to change when each setTimeout method will run.
setTimeout(function(){
alert(
"
45 seconds left"
)}, 5000); //50-5=45
setTimeout(function(){
alert(
"
40 seconds left"
)}, 10000); //45-5=40
Notice the second setTimeout will run after 10000 milliseconds, or 10 seconds. So you just have to continue doing that.
setTimeout(function(){
alert(
"
45 seconds left"
)}, 5000); //50-5=45
setTimeout(function(){
alert(
"
40 seconds left"
)}, 10000); //45-5=40
setTimeout(function(){
alert(
"
35 seconds left"
)}, 15000); //40-5=35
etc…
setTimeout(function(){
alert(
"
BLAST OFF!!!"
)}, 50000); //5-5=0
One final thing, you said you had to use a currTime variable. You simply can initialize this to 50 like you said above BEFORE all of the setTimeout methods, and decrement the variable by seconds when each setTimeout method is run. You can then use the value of this in say the alert box.
let currTime = 50;
setTimeout(function(){
currTime-=5;
alert(currTime +
"
seconds left"
);}, 5000);
setTimeout(function(){
currTime-=5;
alert(currTime +
"
seconds left"
);}, 10000);
etc…
Hope this helps and let me know if you have any more questions!
Also, make sure you have a place to run your JavaScript code so you can test it. This site is great and shows you any errors it detects. So if you put your old code in it, it would have told you the issue with the quotation marks.
https://playcode.io/javascript/