Functions, Timers, Events, and Callbacks

R. Alexander Miłowski

School of Information, UC Berkeley


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) {
      } else {
   return S;
What is the difference between fibonacci and fibonacci() ?


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() {
var interval = setInterval(logSomething,1000); // once every second

Or cancel them:


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.



Some common events:

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() {
var div = document.getElementById("#somebit");

and you can remove it:


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).