bigbadbrain logo
bbb Home
  Lesson 9 - Periodically Move Target

SUMMARY

In this lesson you will learn how to use a timer to move the target at periodic intervals.   

DISCUSSION

The window object has many methods.  You have already learned about some of these such as window.alert() and window.open().  Another method is setInterval().  This method causes an action to occur at  specified interval of time:

     timerName = window.setInterval("action", interval) 

  • timerName defines the name of the timer.  It is used for turning off the timer
  • action is a function that will be executed at the specified interval
  • interval is the period of time in milliseconds.  1000 milliseconds equals 1 second.

Once a timers starts, it will execute the action at the specified interval until the timer is turned off.  A timer can be turned off using the clearInterval method: 

     window.clearInterval(timerName)

The example below illustrates the use of the setInterval method.  On lines 11 to 13, <script> is embedded in the <body>. When the page loads, this <script> executes.  On line 12, a timer called timerX is started using the setInterval method.  You could use just about any name for the timer.  The action in this example is alert('hi'). This action will occur every 2000 milliseconds (2 seconds).

Lines 4 to 7 define a function that turns off timerX using the clearInterval method.  This function is called on line 15 in the onclick event for the button.

EXAMPLE - window.setInterval("action", interval)

 Font Size: 8pt 10pt   View Large Version
 Ctrl-C to Copy
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17

PRACTICE

In  the example above:

  1. Modify line 12 so that the alert is displayed every 5 seconds.
  2. Modify line 12 so that the button moves to a new location everytime the timer ticks.

GAME DEVELOPMENT

Modify your game page (game.htm) as follows:

  1. When the user clicks the start button, a timer starts.
  2. The timer causes the moveTarget function to be executed every second.
 
 
©dfx interactive, inc. Contact us at bigbadbrain@bigbadbrain.com