music
OSdata.com: programming text book 

OSdata.com

timer: adding clock and timer in JavaScript

summary

OSdata RSS
News Feed


OSdata blog RSS.

OSdata blog RSS - add to Bloglines
OSdata blog RSS - add to Google Reader.
OSdata blog RSS - add to My AOL
OSdata blog RSS - add to Newsgator.

    This section discusses how to create a timer and clock in JavaScript.

    We will be using this basic facility to implement a wide variety of special operations, including animation.

working example

TIME:
starting
HOURS: 0
MINUTES: 0
SECONDS: 0
1/10th SECONDS: starting
1/100th SECONDS: starting

license

    This is example code from OSdata, This Side of Sanity, and Twiddledom, released under Apache License 2.0.

    Copyright © 2012, 2013, 2014 Milo

    Licensed under the Apache License, Version 2.0 (the “License”); you may not use this file except in compliance with the License. You may obtain a copy of the License at

        http://www.apache.org/licenses/LICENSE-2.0

    Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an “AS IS” BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License.

previous page   next page
previous page
404 page not found redirect
  next page
object oriented website
Google

timer: adding clock and timer in JavaScript

summary

    This section discusses how to create a timer and clock in JavaScript.

    We will be using this basic facility to implement a wide variety of special operations, including animation.

    This code is written in JavaScript because we want it to run in the web browser.

    See the working example above.

script block

    We indicate a block of JavaScript code by using the following tags (minus the notes):

<script type="text/javascript"> Note 1
<!-- Note 2

/* your JavScript goes here */ Note 3

//--> Note 4
</script> Note 5
<noscript>alternative goes here</noscript> Note 6

    1: The first tage starts your JavaScript.

    2: The HTML comment tag makes sure that older browsers don’t get confused and start visibly printing out your JavaScript code in the middle of your web page. This isn’t much of a factor anymore, but it’s just a few extra characters to type.

    3: This line will be replaced with actual JavaScript code.

    4: End the HTML comment. One bit of messiness is that you start it with the JavaScript for commenting out an entire line. This prevents the JavaScript interpretter from accidentally thinking that your HTML end of comment tag is actually JavaScript. One error in JavaScript can stop the entire JavaScript programming from working.

    5: Back to pure HTML now and this tag ends the JavaScript interpretation.

    6: Place your alternative to JavaScript here (while JavaScript is always on in mobile devices, it can manually be turned off by a user on a computer). It often is simply a message that you must have JavaScript turned on to run the web page, but it is better if you actually degrade gracefully and provide a less featured alternative version in plain HTML (we can’t in this example). Any browser old enough that it doesn’t know what the script tag is will ignore your JavaScript because of the HTML comment tags and will also ignore the noscript tags, but will present anything in between the noscript tags as regualr HTML.

    Your JavaScripts can be palced at a number of different locations. The most common are in the head block, at the beginning of the body block, inline with the HTML, and at the end of the body block.

    We are going to place this JavaScript in the head block so that it is loaded before rendering the web page.

global variables

    Next we set up a few global variables.

    The intervalhandle variable is used to store the function that runs the timer.

    The stopflag variable is used to start and stop the timer.

    The variables variables ending in counter are used to store counters for hours, minutes, seconds, tenths of a second, and hundredths of a second. You can go as fine an interval as thousandths of a second, but we are running at a frame rate of 100 frames per second for our upcoming animations (future lessons).

/* GLOBALS (property of window object) */

var intervalhandle;

var stopflag = false;

var hourcounter = 0;
var minutecounter = 0;
var secondcounter = 0;
var tenthsecondcounter = 0;
var hundredthsecondcounter = 0;

target HTML

    We need a target for our clock and timer.

    This is a div and a few span tags. These are placed anywhere in the body of your web page.

<div style="width:640px;margin-left:auto; margin-right:auto;text-align:center;color:black;background-color:white"><p align="center">TIME: <br><span id="timerelement" style="font-size:144px">starting</span><br>HOURS: <span id="hourelement">0</span><br>MINUTES: <span id="minuteelement">0</span><br>SECONDS: <span id="secondelement">0</span><br>1/10th SECONDS: <span id="tenthelement">starting</span><br>1/100th SECONDS: <span id="hundredthelement">starting</span></p></div>

    Each of the spans has an id that is used to target our JavaScript. We will have our function update the visible text at the appropriate times.

clock function

    Now we need a function that runs our clock and timer. The following function will update the clock:

function checktimedispatcher() {

var currentdate=new Date();
var currenttime= currentdate.toLocaleTimeString();
document.getElementById("clockelement").innerHTML= currenttime;

} /* END FUNCTION checktimedispatcher */

    The checktimedispatcher function goes inside the script section of your head section.

    The new Date() will create a new date object, that has the date and time. We store this object in the currentdate local variable.

    We then extract a string with the current local time (local ot the web browser and the computer or mobile device running our JavaScript) from the date object with the toLocaleTimeString method.

    And finally we place this time string into our web page by targetting the span with the id of clockelement using the innerHTML method of the getElementById method (make sure you use the correct capitlization) of the web page (document).

    The getElementById method picks out which tag to change.

    The innerHTML method changes the HTML. In this case we are assigning a raw text string, but in future cases we will be building up entire HTML with text, tags, images, and other cool stuff.

    Note that we are changing the display 100 times a second, which is overkill because the time actually changes only once per second. I urge the reader to do a little study and experimenting to only change the text when a new second starts.

body tag

    The one last thing you need to do to get this function running is to add the function call to the body tag.

<body text="#ffffff" bgcolor="black" onload="intervalhandle=window.setInterval(function() {checktimedispatcher() },10);">

    The onload event runs our function once the entire web page has been loaded. If we start the function before the browser has rendered our target spans, then the JavaScript will fail and stop running. It won’t restart once the spans are finally rendered.

    The onload event will also make sure that our clock and timer starts running automatically without the user having to clic a button or do anything.

    The setInterval method will add the designated function and run that function every o1/100th of a second. The number 10 means to run once every 10 milliseconds. We save our reference in the intervalhandle variable.

test

    If you place all of these parts into the correct location in an HTML document, you can run it from your local machine by just dragging the document into a browser window. If you have done everything correctly, then your clock will work. Otherwise, you can start debugging before things get more complex.

timer

    Now we are going to insert our timer.

    Place the following code in the checktimedispatcher function after the previous code:

hundredthsecondcounter = hundredthsecondcounter +1;
document.getElementById("hundredthelement").innerHTML= hundredthsecondcounter;
if ( (hundredthsecondcounter%10) == 0 ) {
  tenthsecondcounter = tenthsecondcounter +1;
  document.getElementById("tenthelement").innerHTML= tenthsecondcounter;
  if ( (tenthsecondcounter%10) == 0) {
    secondcounter = secondcounter + 1;
   document.getElementById("secondelement").innerHTML= secondcounter;
    if ( (secondcounter%60) == 0) {
      minutecounter = minutecounter + 1;
      document.getElementById("minuteelement").innerHTML= minutecounter;
      if ( (minutecounter%60) == 0) {
        hourcounter = hourcounter + 1;
        document.getElementById("hourelement").innerHTML= hourcounter;
      } /* END hour check */
    } /* END minute check */
  } /* END second check */
} /* END tenth second check */

    The cascading if statements let us sort which timers get updated.

    We always update the hundredthsecondcounter and update the corresponding hundredthelement span on the web page.

    We use the mod operator % to update the tenthsecondcounter and update the corresponding tenthelement span on the web page.

    We use the same technique for the seconds, minutes, and hours.

    Please add this code to your function and make sure your timer works.

start, stop, reset

    Now we implement our start, stop, and reset buttons.

    First we add some code to the existing checktimedispatcher function. This new code fragment goes between the writing of the clock element and the cascading if statements.

if (stopflag == true) {
  return;
} /* don't change the timers if we have stopped timing */

    This either allows or prevents the update of the timers.

    Now we add the functions lthat start, stop, and reset the timers. Place these functions in the script area of the head of your document. These functions can be in any order you desire.

function starttimer() {

stopflag = false;

} /* END FUNCTION starttimer */

    We start the timer by setting the stopflag to false. It really is that easy, because our checktimedispatcher checks the flag and allows the timer updates if the flag is false.

function stoptimer() {

stopflag = true;

} /* END FUNCTION stoptimer */

    We stop the timer by setting the stopflag to true. It really is that easy, because our checktimedispatcher checks the flag and skips the timer updates if the flag is true.

function resettimer() {

hourcounter = 0;
document.getElementById("hourelement").innerHTML= hourcounter;
minutecounter = 0;
document.getElementById("minuteelement").innerHTML= minutecounter;
secondcounter = 0;
document.getElementById("secondelement").innerHTML= secondcounter;
tenthsecondcounter = 0;
document.getElementById("tenthelement").innerHTML= tenthsecondcounter;
hundredthsecondcounter = 0;
document.getElementById("hundredthelement").innerHTML= hundredthsecondcounter;

} /* END FUNCTION resettimer */

    The resettimer function works by simply setting all of our counter variables back to zero and then updating their new values with the appropriate getElementById and innerHTML methods.

    And we update the body of our HTML web page by inserting simple buttons that trigger each of the three functions:

<p align="center"><button type="button" onclick="starttimer();">Start</button> <button type="button" onclick="stoptimer();">Stop</button> <button type="button" onclick="resettimer();">Reset</button></p>

    The button tag is new as of HTML 4, so it won’t display in older browsers.

    Add the functions and buttons and test your work so far.

    See the working example above.

count down

    The script as provided only counts up. Test your knowledge of the coding you have just done by rewriting it to count down.

    Or even have the option of both counting up or down. Hint: You can create a upordown variable and stick it into the cascading if statements in the place of the +1. If you want to count up, then add plus one. If you want to count down, then add negative one. Your functions will simply change the value of the upordown variable to either 1 or -1.

    Also, think about what happens when your count down reaches zero. You need to write some code to both stop the timers at zero and to prevent some of your timers from accidentally going into negative time.

    You can build all of that with just the code you have seen so far in this example. Start the timer running up, then switch direction.

    But what if you want to have a specific start time for your count down? Well, you can easily hard code some particular values and use a variation of the resettimer function. Or you can allow input from the user for a user selected count down start time. That will require using techniques beyond those shown in this example. If you are feeling ambitious, you can research on the web how to input and validate user numbers using JavaScript.

installation

    If you have trouble, you can refer to the source code section at timer.html. Please try to build this yourself rather than just copy and paste from the example.

return to source code lessons

return to Outrageous Coder
return to Source Code Examples

previous page   next page
previous page
404 page not found redirect
  next page
object oriented website

contact
comments, suggestions, corrections, criticisms

because of ridiculous spam attacks,
contact through Twitter (@OutrageousCoder) will be more reliable than the contact form

please contact us

your name:
email address:
phone number:
message:

return to Outrageous Coder
return to source code lessons
return to table of contents
free downloadable college text book

license

    This is example code from OSdata, This Side of Sanity, and Twiddledom, released under Apache License 2.0.

    Copyright © 2012, 2013, 2014 Milo

    Licensed under the Apache License, Version 2.0 (the “License”); you may not use this file except in compliance with the License. You may obtain a copy of the License at

        http://www.apache.org/licenses/LICENSE-2.0

    Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an “AS IS” BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License.

previous page   next page
previous page
404 page not found redirect
  next page
object oriented website

Google


Made with Macintosh

    This web site handcrafted on Macintosh computers using Tom Bender’s Tex-Edit Plus and served using FreeBSD .

Viewable With Any Browser


    †UNIX used as a generic term unless specifically used as a trademark (such as in the phrase “UNIX certified”). UNIX is a registered trademark in the United States and other countries, licensed exclusively through X/Open Company Ltd.

    Names and logos of various OSs are trademarks of their respective owners.

    Copyright © 2014 Milo

    Created: May 26, 2014

    Last Updated: May 26, 2014


return to table of contents
free downloadable college text book

previous page   next page
previous page
404 page not found redirect
  next page
object oriented website