{{{{ JavaScript - Odds and Ends }}}}

Timer (universal time)
Timer (time interrupt)
Example - Animation
Start of website

Alphabetical index

Summary of colours in code: green is HTML useful for JavaScript, red is JavaScript, blue is a name and everything else is grey.



Timer (universal time)

We have already met some JavaScript using time, both today's date and the current time. However, in the example below, I time something happening. The user is invited to type ten letters in (these get generated randomly), and then is told how long he took. There are several new features here.

There are 3 global variables, the letter that the user is supposed to type, the number of letters typed so far, and a stopwatch to check time. When you start a go (by clicking on the button), the code sets up the first letter, sets the stopwatch, and sets the number of letters typed so far to zero.

The setting up of the letter uses some rather strange looking code. Computers don't actually understand letters, they only understand numbers. But software interprets some numbers as letters in certain circumstances. Normally the programmer (that is, you and me!) can use letters and leave it to the software to sort out, but sometimes it's usefully to use the number equivalent, as I have here. These are called Unicodes or ASCII codes. All you need to know here is that 97 is "a", 98 is "b" and so on, to 122 which is "z". (If you're interested, then "A"-"Z" is 65-90). This means that we can generate a random letter by taking a random number from 1-26, adding 96 (to give a number from 97-122), and then extracting the required letter, which is what String.fromCharCode(..) does. There are other ways to get a random letter, perhaps by setting up an array of 26 elements, each of which contains a letter (boring to set up!), or a string containing all the letters, and extracting a letter as a sub-string. By the way, if you want to get the Unicode or ASCII code of a letter, then use .charCodeAt(..), for example "str.charCodeAt(0)" gives you the Unicode of the first character of the variable "str", and "str.charCodeAt(1)" gives you the Unicode of the second character of the variable "str". The other things we do when setting the letter up is to output it onto the webpage, of course, and set the focus and the value of the textbox where the user will type in the letter. The user won't want to waste time clicking in the box before typing, so it's important to make sure that the cursor is in the correct place, and you should clear out any previous rubbish there as well.

By the way, if you have a Unicode and want the letter, then use String.fromCharCode(..), for example "String.fromCharCode(65)" gives "A".

The setting of the stopwatch uses new Date().valueOf(). This returns a "universal time" (the time since January 1st 1970 in milliseconds, if youwant to know!) We aren't interested in this actual number, but later I get this type of time again, and subtract the two. This will give me the time between the two in milliseconds.

You should be familiar with the random number generator by now.

Once you've set the letter up, the webpage waits for the user to type in a letter. When he does, ONKEYUP actions "inplet()". This code first checks if the letter typed is the right one. If it is, it checks if we have had 10 letters yet. If not, I set up a new letter, and return to let the user type that. Ten letters signals the end of the go. So I get the time again (see above), and display how long the user took. I have to divide the time by a thousand, since it is in milliseconds, and we want seconds.

By the way, if the user typed in the wrong letter, remember to clear out the wrong letter, or when he types in the correct letter, it will get added to the end of the wrong letter and still be wrong. (And yes - that was another of my program bugs!)

I have explained this code in some detail as it is all getting rather complicated. Some code happens when the page is loaded (the definition of the global variables), some when you click on the "Start go" button, some when you type in a letter, some when you type in a wrong letter, some when you have typed in ten letters, and some in more than one place (where you set up another letter). If you can understand all that, then you have a good grasp of how JavaScript program logic can work.

Type:  
<HTML>
<HEAD>
<SCRIPT TYPE="TEXT/JAVASCRIPT">

// Global variables

var stopwatch = 0
var letter = ""
var num = 0

// start new go

function startgo() {
  setlet()
  var tim = new Date().valueOf()
  stopwatch = tim
  num = 0
}

// set up letter

function setlet() {
  letter = String.fromCharCode(96 + rnd(26))
  document.getElementById('outlet').innerHTML = letter
  document.typing.inp.value = ""
  document.typing.inp.focus()
}

// Random number generator

function rnd(max) {
  var rndnum = max * Math.random()
  rndnum = Math.ceil (rndnum)
  return rndnum
}

// Check letter input

function inplet() {
  if (document.typing.inp.value != letter) {
    alert ("Wrong!\nYou typed "+document.typing.inp.value)
    document.typing.inp.value = ""
    document.typing.inp.focus()
    return
  }

  num++
  if (num < 10) {setlet(); return}

  var tim = new Date().valueOf()
  stopwatch = tim - stopwatch
  alert ("You took "+ stopwatch / 1000 + " seconds")
}
</SCRIPT>

</HEAD>
<BODY>
<BR>
<FORM ACTION="#" NAME=typing>
<INPUT TYPE=BUTTON VALUE="start go" ONCLICK="startgo()">
<INPUT TYPE=TEXT NAME="inp" SIZE=1 ONKEYUP="inplet()">
</FORM>

Type:
<FONT SIZE=7>&nbsp;<SPAN ID="outlet"></SPAN></FONT>
</BODY>
</HTML>




Timer (time interrupt)

There is another way to time things happening. In the previous example, I let the user type ten letters and time how long it took. In the example below, I let him type letters for thirty seconds, and he can see how long that took. You could do that using universal time, as above. You would have to look at the time after each letter typed, and see if you have reached 30 seconds yet. However, the example below uses a timer interrupt instead. You can see that most of the code is identical (except I have had to change most of the names, so I could run two similar pieces of code on the same webpage - BORING!) However, there is not a "stopwatch" variable anymore, and instead of using new Date().valueOf(), there is a new statement setTimeout("tick()",30 * 1000). What this statement says is - Set up a timer interrupt for 30 seconds. When that time has elapsed, run the function "tick()". The number "30 * 1000" is the length of time. I could have written 30000, but I wrote it this way to make it easier for you to change. The time is in milliseconds (again), and too many zeros are confusing, I've found. Since we have set the interrupt up, we don't need to test for anything (apart from the letter itself) when a letter is typed. Once 30 seconds is over, the code for "tick()" is automatically actioned.

You must be careful with timer interrupts. It is quite possible to have more than one timer interrupt running at the same time, or even to produce more and more timer interrupts, which gives you a particularly ugly infinite loop. Make sure that only one timer interrupt is happening at any one time. If you are having trouble with this, you may need to have a variable which you set when you set up a timer interrupt, and don't set any more until that one has finished!

Type:  
<HTML>
<HEAD>
<SCRIPT TYPE="TEXT/JAVASCRIPT">

// Global variables

var let = ""
var numb = 0

// start new go

function stgo() {
  setletter()
  setTimeout("tick()",30 * 1000)
  numb = 0
}

// set up letter

function setletter() {
  let = String.fromCharCode(96 + rnd(26))
  document.getElementById('outletter').innerHTML = let
  document.typ.inpt.value = ""
  document.typ.inpt.focus()
}

// Random number generator

function rnd(max) {
  var rndnum = max * Math.random()
  rndnum = Math.ceil (rndnum)
  return rndnum
}

// Tick of the clock

function tick() {
  alert ("You typed "+ numb + " letters in 30 seconds")
}

// Check letter input

function inlet() {
  if (document.typ.inpt.value != let) {
    alert ("Wrong!\nYou typed "+document.typ.inpt.value)
    document.typ.inpt.value = ""
    document.typ.inpt.focus()
    return
  }
  numb++
  setletter()
}
</SCRIPT>

</HEAD>
<BODY>
<BR>
<FORM ACTION="#" NAME=typ>
<INPUT TYPE=BUTTON VALUE="start go" ONCLICK="stgo()">
<INPUT TYPE=TEXT NAME="inpt" SIZE=1 ONKEYUP="inlet()">
</FORM>

Type:
<FONT SIZE=7>&nbsp;<SPAN ID="outletter"></SPAN></FONT>
</BODY>
</HTML>


Another place that timer interrupts are used is in animation (changing pictures), or something like the time displayed on your webpage, which you want to change every second, or minute, perhaps.



Example - animation

I would prefer to use a moving gif for animation. You can construct a moving gif using software like Paint Shop Pro's Animation software. However, if you don't have this then you could do it yourself using JavaScript, as below. I have used the pictures from a previous example. There are 9 pictures, called 'horse1.gif' to 'horse9.gif'. The change picture routine adds one to the picture counter 'num' and adjusts it if it's got too high. Then it starts a timer interrupt of 1/10 second (remember that the timer interrupt counts in thousandths of a second). This is called once from the main body of the webpage, which produces the first picture. After 1/10 second, the timer interrupt runs out, and it gets called again, to change the picture to the next one, and so on.

 <HTML>
<HEAD>
<SCRIPT TYPE="TEXT/JAVASCRIPT">

// Global variables

var num = 0

// Change picture

function changepic() {

  num++; if (num > 9) {num = 1}
  document.images['horse'].src = 'horse' + num + '.gif'
  setTimeout("changepic()",100)
}
</SCRIPT>

</HEAD>
<BODY>
<IMG SRC="horse1.gif" NAME="horse">
<SCRIPT TYPE="TEXT/JAVASCRIPT">
changepic()
</SCRIPT>







Return to JavaScript index



Valid HTML 4.01!

© Jo Edkins 2005