Skip to content Skip to sidebar Skip to footer

How To Eliminate Unused Arguments In An Opacity Fade?

element is called but never used, they are just passed back to a another function call. This seems like a waste is there a better way to do this? Initial Call fadeUp( document.get

Solution 1:

The element argument is used in the callback function. If you eliminate it from the fadeUp() function, then it will not be available to the callback function and your code will not work. This is the proper way to pass element for use in the callback and there is not a better way to get that argument to the callback function.

If I follow what you're trying to do, then I think you can use this much simpler code that uses no static variables:

function fadeUp( element, max_time ) {
    var elapsed = 0;

    function next() {
        elapsed += 10;
        element.style.opacity = Math.min(elapsed / max_time, 1);
        if (elapsed <= max_time) {
            setTimeout(next, 10);
        }
    }
    next();
}

You can see it work here: http://jsfiddle.net/jfriend00/FHq6B/.

This uses a local function and local variables with no static variables.

And, a slightly more accurate version that uses actual elapsed time to calculate the amount of fade would look like this:

function fadeUp( element, max_time ) {
    var startTime = (new Date()).getTime();

    function next() {
        var elapsed = (new Date()).getTime() - startTime;
        element.style.opacity = Math.min(elapsed / max_time, 1);
        if (elapsed <= max_time) {
            setTimeout(next, 10);
        }
    }
    next();
}

This one can be seen here: http://jsfiddle.net/jfriend00/g98Tv/.

Note the additional accuracy of using actual elapsed time is probably not noticeable with a fade animation, but can be noticeable with other types of animations which is why I included it here.


Post a Comment for "How To Eliminate Unused Arguments In An Opacity Fade?"