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`

12<div></div><img id="picture" src="picture.jpg" alt="" width="100" />`interval.js`

1234567891011var w;var timerId;function zoom() {w = Number(document.getElementById('picture').getAttribute('width'));timerId = setInterval('change();', 100);}function change() {w += 10;document.getElementById('picture').setAttribute('width', w);if (w > 1000) {clearInterval(timerId);}}

*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`

123<div></div><div></div><div></div>`random.css`

1234p.result {font-size: xx-large;color: red;}`random.js`

123function janken() {var x = Math.random();if (x < 1/3) { y = 'Rock'; } else { if (x < 2/3) { y = 'Paper'; } else { y = 'Scissors'; } } document.getElementById('result').innerHTML = y; }- We can rewrite
`random.js`

as follows:

12345function janken() {var x = Math.floor(Math.random()*3);var y = ['Rock', 'Paper', 'Scissors'];document.getElementById('result').innerHTML = y[x];}