Function with Argument, Sensors

Goals

In this lesson we will handle functions as event handlers and execute them when events occur. Today we will learn about more complex functions that can be used in web programming

  • Understand the concept of functions.  
  • Learn how to create and call functions using arguments.    
  • Learn how to call functions created by others.    
  • Understand the concept of the callback function.
  • Learn how to develop a callback function to acquire sensor information.

Functions and Arguments

When calling a function, you can pass a value into it. The value passed to the function as an argument is assigned to a variable described as the parameter of the function. It can be referred to anywhere within the function’s scope. Within the parameter of the function body, we do not need to declare it using the keyword var.

JavaScript

function sum(num1, num2){
    alert(num1 + num2);
}

sum(20, 15);
// 35 is output

In the example above, calls to the sum () function on line 5 pass the numbers 20 and 15 to the sum () function. Such values are called arguments. The actual sum () function is defined from the first line to the third line.

In parentheses on the first line, variables num1 and num2 are specified. These are variables for receiving arguments for function calls, called dummy arguments. When a function is called, it operates with a value in the variable specified by the dummy argument. That is, in the above example, the calculation result of num 1 + num 2, that is, 35 is displayed by using the alert () in the second row.

The following figure shows the concept of functions, dummy arguments, and return values so that they can be more intuitively understood. The green part in the program on the left is executed in such a way that it is expanded to the function on the right. In this example, the return value is introduced in addition to the argument.

In this example, a function called add () is defined and used. The function called add () has two parameters, x and y as dummy arguments. In the function, these two variables are added and stored in another variable z, and z is returned to the original program by using the return statement.

Let’s look at the calling program. We define a variable called a and initialize it with 2. In the next line, the variable sum is defined. At the next assignment statement, a function called add () comes up. In calling the add () function, a value of 1 and a variable called a are specified as arguments. When the function is called, control temporarily moves to the function side, but at this time, the value specified as the argument is set to the dummy argument of the function. In this example, x is set to 1, y is set as 2 in a. Therefore, when z = x + y in the add () function is executed, x is 1, y is 2, and z is 3. After that, the return statement which is the last line in the add () function shows that the value that the function finally returns to the calling program is z. This value is called a return value. Therefore, on the caller side, the evaluation result of add (1, a) is 3, and as a result, 3 is substituted into the variable sum.

JavaScript

// called function add()
function add(x, y) {
    var z = x + y;
    return z;
}

// Calling function
function lec01_02_click() {
    var a = 2;
    var sum;

    sum = add(1, a);

    alert('sum = ' + sum);
}

Callback Function

Since JavaScript expresses all values as “objects”, anything can be stored in a variable. Therefore, you can pass functions as arguments when calling functions. It is possible to create a mechanism in which a function is registered as an argument. For example, the function is called by some event such as the completion of a process, and as a result the value of the sensor changes. A function registered in preparation for such an event is called a callback function. For specific examples, please refer to the section on how to use the sensor from the next chapter.

Ambient Light Events

The Device APIs Working Group of the World Wide Web Consortium (W3C) standardizes the API for using many sensor information. Among them, there is an illuminance sensor that can be used with iMac. Let’s use it here.

Look at the next program. In the HTML section, a text area is created, followed by the unit “lux”. lux is a unit representing illuminance. In the JavaScript section, we first define a function called light_print (). This function is a callback function called when there is a change in illuminance.

Since it is decided by the API that a function to be called when the illuminance is changed takes one argument, its argument is received as a formal argument “event”. From the 2nd line to the 3rd line, the text area is acquired and the actual illuminance value is set in the text area. The sixth line is the part executed when the program is read. Here, ‘devicelight’ represents an illuminance sensor. When there is a change in the value of the illuminance sensor, light_print () set as the second argument and is called. Please note that once you set it, this function will be called each time the value changes.

HTML

<input type="text" id="lighttext" value="Change the exposure of your computer camera please"> lux

JavaScript

function light_print(event) {
	var elm = document.getElementById('lighttext');
	elm.value = event.value;
}

window.addEventListener('devicelight', light_print);

The iMac’s illuminance sensor is next to the camera. When you move your hand over or away from the camera part, the value detected by the illuminance sensor changes.

The use of sensor information in JavaScript is still in the development stage. Although it is already supported by many smartphones, even fixed PCs often have sensors built in, they cannot be used with JavaScript in many cases. Also, the functions that can be used also depend on the browser. Actually, the light sensor can be used in Firefox, but it cannot be used in Mac OS X’s Safari.

Timer

When you start to use sensor information etc, you may want to process it regularly. We will now learn how to use timers in JavaScript.

In JavaScript, it is possible to use two types of timers: a type that calls the function specified after the specified time, and a timer that calls the specified function periodically. In the former case, once the function is called, it is terminated. In the latter case, for example, the function is called repeatedly every 3 seconds.

Look at the program below. In this program, we first define a callback function called timeout_callback (). When this function is called, an alert is displayed. In the fifth line, timeout_callback () is set to be called after 10000 ms (10 seconds later). Therefore, when this program is executed, an alarm written as “timeout!” Is displayed after 10 seconds.

JavaScript

function timeout_callback() {
  alert("timeout!");
}

setTimeout(timeout_callback,10000);

Also, although it is a similar program, the next program behaves slightly differently. The difference with the above program is that the fifth line is not setTimeout (), but only setInterval (). In this program, unlike the above, timeout_callback () is called every 10 seconds, and as a result, an alert is displayed every 10 seconds.

JavaScript

function timeout_callback() {
  alert("timeout!");
}

setInterval(timeout_callback,10000);

Also, in order to start and stop the repeatedly called timer, it is necessary to specify a timer. Since the setTimeout () and setInterval () functions return a timer object when called, you can stop the timer by storing it in a variable.

In the next program, it is possible to start and stop the timer by storing the value returned by setInterval () in a variable called timer. timeout_callback in setInterval () is the name of the function to be called when timeout occurs.

HTML




<figure class="frame">
<button onclick="startTimer()">Start</button>
<button onclick="stopTimer()">Stop</button>

JavaScript

var timer = null;

function startTimer() {
    if (timer == null)
        timer = setInterval(timeout_callback, 3000);
}

function stopTimer() {
    if (timer != null)
        clearInterval(timer);
    timer = null;
}

Exercise 9-

As shown below, call the day and time as arguments, create a function that returns the subject name you are taking during that time. However, if a day-of-the-week that does not have any classes is entered, it shall be returned as “There are no courses that have been taken.”

...
var week = "mon";
var period = 1;
var title = classTitle(week, period);
...

In addition, if you create two text areas and one button, enter the day and time in each text area and press the button. Once you do, display the subject name you are registered in during that time.

Hint: Have data on the function side.

Exercise 9-

Create a web page whose value of illuminance varies as shown below by the illumination change shown in the example above.

Exercise 9-

Create a program that will create a moving bar graph when the illumination changes. Look below for a demonstration.

Exercise 9-

Create a program that will display an alert saying “alarm timeout” only once, and then after 10 seconds once the user presses the start button.

Exercise 9-

Use setInterval() to create a program that displays “timeout!” with an alert every 10 seconds after pressing the start button. Also, create a way to stop the alerts by pressing the stop button.

Exercise 9-

Create a program that takes string input through a text box, and on pressing a button, displays the characters in a string one by one in the p element prepared beforehand. The letters should be displayed one at a time after every second.

For example, if “keio” is entered in the text area and the button is pressed, display “k” in the first second, “ke” in the second second, “kei” in the third second, and “keio” in the fourth second.

Tip: To retrieve the nth character of the string, use charAt(). Use a timer to delay the display.

Exercise 9-

Create a program such that the bar chart shows the value of luminescence entering the sensor of your computer. Look at the example below for reference.