Appendix: Various Features

We introduce some features that may be useful for the final project.

Iteration by Timer Events

We have learned how to call a function by a timer in Exercise 06-10. In addition, we can call a function repeatedly without any interaction.

An interval timer invokes a JavaScript function repeatedly with a certain interval.

To set the timer, execute:

  • variable = setInterval(function, interval);

function is the function name and interval is a number representing the interval in millisecond. The ID of the timer is stored into variable – this ID is used when you need stop the timer.

To stop the timer, execute:

  • clearInterval(timerID);

A sample program is shown below. (We assume an image file picture.jpg exists in the same directory)

  • interval.html
  • interval.js

funtion in setInterval can be specified with a function name alone. So, the 6th line above is equal to:
timerId = setInterval(change, 100);

Random Number

Calculation using a mathematical formula should always result in the same output when the inputs are constant. However, in some computer program, it is more convenient when we can get different values each time we calculate. As an example, random numbers are essential in video games in order to randomize the enemy’s behavior.

Random numbers are a sequence of numbers that are unpredictable. In JavaScript, a function Math.random() calculates (pseudo) random numbers. Math.random() allows different numbers to be generated each execution.

Math.random() returns a decimal number no less than 0 and less than 1. In case we want to get a random element of an array, we need an integral random number. To convert decimal to integer, we use multiplication and a round-down function Math.floor(). For example, to get an integer between 0 and 9, execute:

  • Math.floor(Math.random()*10)

Below is a smaple program to display one of rock, paper and scissors randomly.

  • random.html
  • random.css
  • random.js
  • We can rewrite random.js as follows: