Easy-to-follow video tutorials help you learn software, creative, and business skills.Become a member

Example: Countdown

From: JavaScript Essential Training

Video: Example: Countdown

So let's put several of these ideas together. I'm going to run through a few examples to use the techniques and the concepts we have already explored in combination with each other. And the first example I going to do here is this Countdown page, where I can type into the text box, put in, say, 3, and click the button to say Start Countdown, and I get this little JavaScript timer going on. And this is not spectacularly impressive, I grant you, but as you'll see, it's a good example of several techniques put together.

Example: Countdown

So let's put several of these ideas together. I'm going to run through a few examples to use the techniques and the concepts we have already explored in combination with each other. And the first example I going to do here is this Countdown page, where I can type into the text box, put in, say, 3, and click the button to say Start Countdown, and I get this little JavaScript timer going on. And this is not spectacularly impressive, I grant you, but as you'll see, it's a good example of several techniques put together.

Now step one, I have chosen to make this page as simple as possible, so we can focus on the script. And in fact, if I look at the HTML here, I can see there really isn't much going on. I have got a little bit of basic CSS at the top, but body of the page itself is simply a container div which inside has another div which has nothing in it and one h1. And in fact on this page itself I don't have the HTML for the text box or this button. I'm going to generate that content through JavaScript, and then I am going to add the logic to work with it.

So let me open the JavaScript and show you what's going on here. First off, I have the window.onload anonymous function here. So as soon as the page is loaded, I'm going to run this code. And what we are doing here is creating a couple on new elements. I am using document.createElement here to create a new input element. It's going to be a text box, and I'm going to give it an ID of minutes. Then I'm going to create a button. Again it's an input element, but this one has a type of button. I will give it some text, which is "Start Countdown," and then I'm going to associate the click event of that button with a function called startCountdown, which we will explore in a second.

And then finally these last two lines simply take my two new elements and they add them to the div called inputArea. So that's what creates these parts of the page. Now if I put in, say, some text here and click this button, it's going to pop up on alert called Please enter a number! which makes sense. Let's see what's happening. I said the click event is associated with the function called startCountdown, and here it is. The first thing we do is try and grab the contents of that text box, which we are using the.value property of, and then I am using the isNaN function to check, is it not the number? So if this minutes variable is not a number, I will pop up an alert, and then I am just going to hit return, which basically means I'm done with this function, I'm not going any further, I can't do anything else it doesn't make sense anymore.

Now however, if it is a number, we will just scoot right past that if statement and then what I will do is I will find out how many minutes they typed in, I will multiply that by 60, and I will store it in the variable called secondsRemaining. Now, secondsRemaining is a variable that's actually declared right at the top of my JavaScript. It is a global variable of which I have two, just because I'm going to use those from different functions. So we create it there. What I'm then going to do is called the setInterval function. This is the one that calls a method repeatedly. And the method we are going to call is tick, and we are going to call tick every 1000 ms, which is one second.

And if you remember from when we originally talked about setInterval, if you ever want to be able to clear the interval, i.e., to stop this interval from reoccurring, you need to grab a variable to it. You need to grab a handle on it, which you can then call later to call clearInterval. So we count the number of seconds. We kick off the tick function every one second, and then what I am going to do is actually hide--it's not really a form, but I am going to hide that input area that has the text box and the button, because I don't need to show it when the clock is ticking.

So this must be more interesting function, which is tick, which is defined a little bit up here. Let's bring this up and just going through this one, first line I will grab hold of a variable called timeDisplay, and that is simply grabbing hold all of h1, which is showing the time. So it's just grabbing hold of this part of the page. Then what I'm going to do is turn the seconds that I have, which is stored in the seconds remaining variable, into minutes and seconds. The first thing I do is divide seconds by 60. That will give me the amount of minutes and then some number after the decimal point.

So I use what's called the Math.floor function, so that's a built-in part of JavaScript, to say I want to take something that might be 4.2 and make it just 4, just make it a basic integer with nothing after the decimal point. Now I am using the term .floor rather than .round because I don't want to round up and round down; I just want to ignore any remainder. I am just interested in the minutes. Now in the same way, what I can do in this next line is just figure out what the seconds remaining are, and I am just going to subtract minutes * 60 from seconds remaining.

That will give me the remainder. Several ways of course I could calculate this. On line 18 I am asking one question: how many seconds are left? And if those seconds are less than 10, I want to add a leading 0 to it, because if we are counting down, I don't want it to say 1:1. Most digital watches and so on will always have a leading zero when your seconds get down beyond 10. So this is what I'm doing here, and I am using 0 as a string, so in the double quotes, so that when these two are added together, it will turn the number 5 into 05 or the number 9 into 09.

I finally take both my min variable and my seconds variable and add them together. If you are bothered about official type conversion, meaning that if min is a number, how can I explicitly say it's a string, I could use the dot to string method here. I don't need to do that. This would work just fine. This concatenation will join the number that's stored in min, then a colon, and then finally, we change what the page actually displays. The last couple of things to check is did our seconds get down to 0, and if so, we can pop-up an alert saying we are done.

We don't need to start calling this tick function anymore. So I will click clearInterval, and I will finally call resetPage, which is going to show the section of the page that would allow me to kick the countdown off again. And the very last line here is subtract one from seconds remaining, because this is a function that's called every second. We want to make sure that we are counting down. Finally, the resetPage function is this one line here that's going to make the input area display itself again. And that's what's going to allow us to do a little bit of error checking here and then feed in a little bit of information.

And sure, this might be a simple example, but we are using it to do all the common JavaScript tasks. We are creating DOM elements, actually creating the page content dynamically through JavaScript. We are using events, both the window.onload event and also the button.onclick event. We are doing error checking of the input, making sure that in this case it is a number before we try and do anything with it. We are creating intervals to repeatedly call functions every second.

We are hiding and showing parts of the page. We are using the Math object to do our calculations. We are popping up alerts, and we are grabbing and changing elements, and these are all the same things that you will be doing in every JavaScript program. Now, this example certainly isn't perfect. I could add more error checking to check for a minimum and maximum value. I could generate a pause button that might show up when the countdown begins. I could make the text change color as it gets closer to zero, and you should be able to figure out several ways this could be improved and extended.

So take a look at it and see what you can do.

Show transcript

This video is part of

Image for JavaScript Essential Training
JavaScript Essential Training

56 video lessons · 104892 viewers

Simon Allardice
Author

 
Expand all | Collapse all
  1. 3m 28s
    1. Welcome
      1m 1s
    2. What you should know
      1m 44s
    3. Using the exercise files
      43s
  2. 15m 41s
    1. Introduction to JavaScript
      8m 6s
    2. Creating your first JavaScript
      2m 13s
    3. Getting to know the tools and applications
      5m 22s
  3. 56m 8s
    1. Understanding the structure of JavaScript code
      7m 9s
    2. Where to write your JavaScript
      3m 56s
    3. Creating variables
      6m 21s
    4. Working with conditional code
      5m 44s
    5. Working with operators
      13m 28s
    6. Sending messages to the console
      2m 59s
    7. Working with loops
      8m 1s
    8. Creating functions
      8m 30s
  4. 36m 13s
    1. Working with arrays
      7m 57s
    2. Working with numbers
      6m 13s
    3. Working with strings
      8m 27s
    4. Working with dates
      5m 38s
    5. Working with objects
      7m 58s
  5. 9m 6s
    1. What is the DOM?
      5m 49s
    2. Working with nodes and elements
      3m 17s
  6. 25m 17s
    1. Accessing DOM elements
      11m 3s
    2. Changing DOM elements
      5m 42s
    3. Creating DOM elements
      8m 32s
  7. 24m 45s
    1. Introduction to JavaScript event handling
      8m 16s
    2. Working with onClick and onLoad events
      7m 36s
    3. Working with onBlur and onFocus events
      2m 36s
    4. Working with timers
      6m 17s
  8. 21m 41s
    1. Common JavaScript errors
      7m 14s
    2. Using Firebug
      4m 7s
    3. Going through a debugging session
      10m 20s
  9. 10m 13s
    1. Accessing form elements
      4m 20s
    2. Preventing a form from being submitted
      2m 36s
    3. Hiding and showing form sections
      3m 17s
  10. 9m 49s
    1. CSS and JavaScript
      3m 46s
    2. Removing and applying CSS classes
      2m 16s
    3. Changing inline styles
      3m 47s
  11. 19m 44s
    1. Understanding JavaScript style
      7m 39s
    2. Minifying your code
      4m 28s
    3. Using JavaScript code checkers
      7m 37s
  12. 22m 24s
    1. Introduction to JavaScript libraries
      3m 17s
    2. Linking to multiple JavaScript files
      2m 11s
    3. Introduction to jQuery
      12m 7s
    4. Using a content distribution network to deliver JavaScript files
      4m 49s
  13. 17m 35s
    1. JavaScript in HTML5
      9m 37s
    2. Using Modernizr
      3m 2s
    3. Using Strict Mode
      4m 56s
  14. 33m 3s
    1. Knowing the JavaScript to avoid
      6m 35s
    2. Introduction to regular expressions
      6m 56s
    3. Working with AJAX
      10m 44s
    4. Working with objects and prototypes
      8m 48s
  15. 21m 10s
    1. Example: Countdown
      8m 3s
    2. Example: Resize
      5m 47s
    3. Example: Accordion
      7m 20s
  16. 4m 58s
    1. Where to go from here
      4m 0s
    2. Goodbye
      58s

Start learning today

Get unlimited access to all courses for just $25/month.

Become a member
Sometimes @lynda teaches me how to use a program and sometimes Lynda.com changes my life forever. @JosefShutter
@lynda lynda.com is an absolute life saver when it comes to learning todays software. Definitely recommend it! #higherlearning @Michael_Caraway
@lynda The best thing online! Your database of courses is great! To the mark and very helpful. Thanks! @ru22more
Got to create something yesterday I never thought I could do. #thanks @lynda @Ngventurella
I really do love @lynda as a learning platform. Never stop learning and developing, it’s probably our greatest gift as a species! @soundslikedavid
@lynda just subscribed to lynda.com all I can say its brilliant join now trust me @ButchSamurai
@lynda is an awesome resource. The membership is priceless if you take advantage of it. @diabetic_techie
One of the best decision I made this year. Buy a 1yr subscription to @lynda @cybercaptive
guys lynda.com (@lynda) is the best. So far I’ve learned Java, principles of OO programming, and now learning about MS project @lucasmitchell
Signed back up to @lynda dot com. I’ve missed it!! Proper geeking out right now! #timetolearn #geek @JayGodbold
Share a link to this course

What are exercise files?

Exercise files are the same files the author uses in the course. Save time by downloading the author's files instead of setting up your own files, and learn by following along with the instructor.

Can I take this course without the exercise files?

Yes! If you decide you would like the exercise files later, you can upgrade to a premium account any time.

Become a member Download sample files See plans and pricing

Please wait... please wait ...
Upgrade to get access to exercise files.

Exercise files video

How to use exercise files.

Learn by watching, listening, and doing, Exercise files are the same files the author uses in the course, so you can download them and follow along Premium memberships include access to all exercise files in the library.


Exercise files

Exercise files video

How to use exercise files.

For additional information on downloading and using exercise files, watch our instructional video or read the instructions in the FAQ .

This course includes free exercise files, so you can practice while you watch the course. To access all the exercise files in our library, become a Premium Member.

Join now Already a member? Log in

Are you sure you want to mark all the videos in this course as unwatched?

This will not affect your course history, your reports, or your certificates of completion for this course.


Mark all as unwatched Cancel

Congratulations

You have completed JavaScript Essential Training.

Return to your organization's learning portal to continue training, or close this page.


OK
Become a member to add this course to a playlist

Join today and get unlimited access to the entire library of video courses—and create as many playlists as you like.

Get started

Already a member ?

Become a member to like this course.

Join today and get unlimited access to the entire library of video courses.

Get started

Already a member?

Exercise files

Learn by watching, listening, and doing! Exercise files are the same files the author uses in the course, so you can download them and follow along. Exercise files are available with all Premium memberships. Learn more

Get started

Already a Premium member?

Exercise files video

How to use exercise files.

Ask a question

Thanks for contacting us.
You’ll hear from our Customer Service team within 24 hours.

Please enter the text shown below:

The classic layout automatically defaults to the latest Flash Player.

To choose a different player, hold the cursor over your name at the top right of any lynda.com page and choose Site preferences from the dropdown menu.

Continue to classic layout Stay on new layout
Exercise files

Access exercise files from a button right under the course name.

Mark videos as unwatched

Remove icons showing you already watched videos if you want to start over.

Control your viewing experience

Make the video wide, narrow, full-screen, or pop the player out of the page into its own window.

Interactive transcripts

Click on text in the transcript to jump to that spot in the video. As the video plays, the relevant spot in the transcript will be highlighted.

Are you sure you want to delete this note?

No

Your file was successfully uploaded.

Thanks for signing up.

We’ll send you a confirmation email shortly.


Sign up and receive emails about lynda.com and our online training library:

Here’s our privacy policy with more details about how we handle your information.

Keep up with news, tips, and latest courses with emails from lynda.com.

Sign up and receive emails about lynda.com and our online training library:

Here’s our privacy policy with more details about how we handle your information.

   
submit Lightbox submit clicked
Terms and conditions of use

We've updated our terms and conditions (now called terms of service).Go
Review and accept our updated terms of service.