window.onload = function() {
var closureOutput = document.getElementById('closureOutput');
var normalOutput = document.getElementById('normalOutput');
var closure = new myClosure();
for(var i = 0; i < 20; i++) {
window.setTimeout(function() {
closureOutput.innerHTML += closure.foo() + "";
normalOutput.innerHTML += myNonClosure() + "";
}, (i*60));
}
}
var myClosure = function() {
var date = new Date();
var myNestedFunc = function() {
return date.getMilliseconds();
};
//object literal
return {
foo: myNestedFunc
};
}
var myNonClosure = function() {
var date = new Date();
return date.getMilliseconds();
}
This is a simple demo to show closure vs non closure. The current milliseconds in the left column are stored in the "myNestedFunc" which is a sub function of "myClosure". Normally these variables are deleted at the end of a function, but by nesting the "myNestedFunc" function we are able to keep any variables that it references alive.
The right column simply echoes the current milliseconds to prodive contrast to the milliseconds stored in the variable.