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 betweenfibonacci
andfibonacci()
?
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().
Imagine you respond to a mouse event and then do a bunch of work. What happens? Everything stops.
Instead:
Some common events:
Event | Description |
---|---|
load | A resource and its dependent resources have finished loading (DOM Level 3). |
click | A pointing device button has been pressed and released on an element. (DOM Level 3). |
mouseover | A 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
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
It is just a function with a particular signature.
Many APIs use callbacks for various state notifications (e.g. the GeoLocation API).