This is my code, SetOpacity get invoked with wrong values, why?
function SetOpacity(eID, opacity){
eID.style.opacity = opacity / 100;
eID.style.filter = 'alpha(opacity=' + opacity + ')';
}
function fade(eID, startOpacity, endOpacity){
var timer = 0;
if (startOpacity < endOpacity) {
for (var i = startOpacity; i <= endOpacity; i++) {
setTimeout(function() {SetOpacity(eID, i);}, timer * 30);
timer++;
}
}
}
This should work:
This works as follows:
function(...){...}) and immediately call it with a parameter (that’s why there are parentheses aroundfunction(){}, so you can call it by adding()at the end and passing parameters)i, which isopacityinside the function) are local to this anonymous function, so they don’t change during the next iterations of the loop, and you can safely pass them to another anonymous function (the first parameter insetTimeout)Your original version didn’t work because:
setTimeoutholds a reference to the variablei(not the value of it), and it resolves its value only when this function is called, which is not at the time of adding it tosetTimeoutsetTimeoutexecutes,iwill have reachedendOpacity(the last value from theforloop)Unfortunately JavaScript only has function scope, so it won’t work if you create the variable inside the loop and assign a new actual value, because whenever there is some
varinside a function, those variables are created at the time of function execution (and areundefinedby default). The only (easy) way to create new scope is to create a function (which may be anonymous) and create new variables inside it (parameters are variables too).