Welcome to the Treehouse Community

The Treehouse Community is a meeting place for developers, designers, and programmers of all backgrounds and skill levels to get support. Collaborate here on code errors or bugs that you need feedback on, or asking for an extra set of eyes on your latest project. Join thousands of Treehouse students and alumni in the community today. (Note: Only Treehouse students can comment or ask questions, but non-students are welcome to browse our conversations.)

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and a supportive community. Start your free trial today.

JavaScript

Darrel Lyons
Darrel Lyons
2,991 Points

Countdown using Javascript

How do i create a simple coundown timer using javascript? I set a time in the database as time() + 60. How do i get this to countdown from 60 to zero and then say Done?

1 Answer

Erik McClintock
Erik McClintock
45,783 Points

Darrel,

You can achieve this by using a loop (for or while, whichever syntax you prefer) that ticks the timer variable down by X during each iteration, where X is however fast you want the timer to count down. Once your timer variable reaches 0, display your message, again with whatever method you prefer (console.log, alert, etc.).

Erik

Erik McClintock
Erik McClintock
45,783 Points

For example:

//declare and instantiate your variable
var timer = 60;

//set up your loop that will run while your variable is greater than zero
while (timer > 0) {
//log timer to the console for debugging purposes
console.log(timer);
//reduce the count of timer by one over each iteration
timer--;
}

//after timer has reached zero, the code will break out of the while loop and run the alert with your confirmation message
alert("Done");

Of course, you could target an element in the document and update its innerHTML with JS at your own discretion, and you'd probably want to wrap the above code in a function and call it a particular time depending on what you need the countdown for, but those are all decisions you would need to make based on the needs of your project.

Erik

Darrel Lyons
Darrel Lyons
2,991 Points

Thanks Eric!! Thanks for using your own time to help me! :)