I really appreciate the explanations/advice. Thanks.
Brian Reindel (
http://blog.reindel.com/2006/09/24/pass-parameters-to-
your-javascript-functions-correctly-from-settimeout-using-oop/) has a
paragraph on setTimeout that helped me get my head around the
complexities of its use (for a newcomer like me):
"If you are moving beyond using JavaScript for simple tasks, and are
building full fledged Web applications, then you will likely make
heavy use of the setTimeout() method available to the window object.
This timer can be powerful, but it also possesses a single shortcoming
that stumps even experienced programmers. There is no "built-in"
mechanism within setTimeout() for calling a function that needs
parameters passed to it...I won't go into the details for all the
different workarounds that currently exist in order to pass in
parameters, as several forums and Web sites do so already. I will
mention that there are two popular techniques: placing an entire
function inside the first parameter (not as a string [i.e. - without
the quotes]), and attempting to use addition operators to build an
expression that represents a function (as a string)."
He advocates an object oriented approach and posts an example.
Per my immediate question about what "+ i +" does, from reading
Reindel I figure I'm "attempting to use addition operators to build an
expression that represents a function (as a string)" whereas Thomas
and timothytoe opt for the "function inside the first parameter"
technique.
The result of the code (see below) is a smooth fade in of an image.
Thomas's suggestion didn't produce the same smooth fade in result as
"+ i +" but timothytoe's did.
So of the approaches (assuming a closure workaround for Thomas's -
beyond me) , what are the relative merits I wonder? (My emphasis as a
newcomer is readability over performance).
Here's what I ended up with (options in a comment block):
function fadeIn() {
var speed = Math.round(500 / 100);
for(var i=0; i<=100; i++) {
/*
Option A per my post:
setTimeout("changeOpacity(" + i + ")",(i * speed));
Option B per timothytoe:
(function(num) {
setTimeout(function() { changeOpacity(num)}, (i *speed));
})(i);
Option C per Thomas: setTimeout(function() { changeOpacity(i) }, (i
* speed));
*/
}
}
function changeOpacity(opacity) {
var object = document.getElementById('someImage').style;
object.opacity = (opacity / 100);
}