I have the following code for a fade animation in Javascript:
var ticks = 20;
function fadein(tick,element){
if(element == null)
return;
element.style.opacity = tick/ticks;
if(tick < ticks) {
var s = "fadein(" + (tick+1) + "," + element + ")";
setTimeout(s, 500/ticks);
}
}
The problem is this line:
var s = "fadein(" + (tick+1) + "," + element + ")";
Element is turned into its string representation and causes an error on the next iteration. I know I could do this if all my elements had IDs by passing the eid, but I want to fade in a lot of different things (at different times) and don’t want to have to name each one. Is there a way to do this in js?
Use an anonymous function instead of the string to call
setTimeout. That way you have easy access to all variables inside thefadeinfunction.Besides this it is considered bad practise to use
setTimeoutorsetIntervalwith a string parameter.