How to eliminate unused arguments in an opacity fade?

后端 未结 1 1355
甜味超标
甜味超标 2021-01-24 03:43

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?

I

1条回答
  •  迷失自我
    2021-01-24 03:59

    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.

    0 讨论(0)
提交回复
热议问题