Javascript: setInterval, setTimeout & callbacks
When using a callback with an object, use an anonymous function to wrap the callback to an object’s method. Otherwise only the function, separated from its object, is called.
var t = {x:12, fun:function(){alert(this.x || "Not defined")}}
//incorrect, will alert("Not defined")
setTimeout(t.fun, 1000)
//the above is identical to
setTimeout(function(){alert(this.x || "Not defined")}, 1000)
// or
var fun = x.fun
setTimeout(fun, 1000)
//The correct way, to preserve access to the function's object instance is
// to wrap the callback in an anonymous function
setTimeout(function(){t.fun()}, 1000)
This is true of setTimeout, setInterval, AJAX or any other asynchronous javascript events.
Another useful tool is the OR operator(double pipes, ||).
t = X || Y
is the same as
if(X == true) { t = X} else { t = Y}
For example:
t = null || 1 // t is 1 t = 12 || 7 // t is 12 t = false || "true" //t is "true"