Functions, Timers, Events, and Callbacks

R. Alexander Miłowski

milowski@ischool.berkeley.edu

School of Information, UC Berkeley

Functions

A function is declared by name:

function name(p1,p2, ...) {
}
               

An example that must be given for every language:

function fibonacci(N) {
   var S = [];
   for (var i=0; i<N; i++) {
      if (i<2) {
         S.push(i);
      } else {
         S.push(S[i-1]+S[i-2]);
      }
   }
   return S;
}
               
What is the difference between fibonacci and fibonacci() ?

Timers

A timer schedules a function to execute in the future or on an interval.

A timeout:

function logSomething() {
   console.log("Hello future!");
}
var timer = setTimeout(logSomething,1000); // one second delay

On on an interval:

function logSomething() {
   console.log("Beuller?");
}
var interval = setInterval(logSomething,1000); // once every second

Or cancel them:

clearTimeout(timer);
clearInterval(interval);

For more information, see MDN setTimeout().

Why timers?

Don't camp on the main thread!

Imagine you respond to a mouse event and then do a bunch of work. What happens? Everything stops.

Instead:

Events

Some common events:

EventDescription
loadA resource and its dependent resources have finished loading (DOM Level 3).
clickA pointing device button has been pressed and released on an element. (DOM Level 3).
mouseoverA pointing device is moved onto the element that has the listener attached or onto one of its children. (DOM Level 3).

For more information, see MDN Event reference

Registering Event Listeners

Registration is by name on the scope: target.addEventListener(type,listener,useCapture)

function ouch() {
   alert("Ouch!");
}
var div = document.getElementById("#somebit");
div.addEventListener("click",ouch,false);
         

and you can remove it:

div.removeEventListener("click",ouch,false);
         

What is the purpose of useCapture ?

For more information, see MDN EventTarget.addEventListener

What is a callback?

  1. A timer?
  2. An interval?
  3. An event listener?
  4. All of the above?

It is just a function with a particular signature.

Many APIs use callbacks for various state notifications (e.g. the GeoLocation API).