Javascript code that only works outside of a function - why?

Why this code does not work as written below, but if I comment function testBgChange(){and save the code inside this function, it works fine. What difference does it make if I save the code inside a function and then call that function?

<html>

<head>

<script type="text/javascript">
    testBgChange();
    function testBgChange(){
        var i = 0;
        var c = 0;
        var time = 3000;
        var incr = 3000;

        while(i<=3){
            if(c==0){
                var red = "#FF0000";
                setTimeout("changeBgColor(red)",time);
                time+=incr;
                c=1;
            }
            else if(c==1){
                var white = "#FFFFFF";
                setTimeout("changeBgColor(white)",time);
                time+=incr;
                c=0;
            }
        i+=1;
        }
    }

    function changeBgColor(color){
        document.getElementById("alert").style.backgroundColor = color;
    }


</script>

</head>
<body>
<p id="alert">
    <br>
    <br>
    Testing
    <br>
    <br>
</p>
</body>

</html>
+2
source share
1 answer

Because var redand var white, declared inside a function, can only be accessed from within a function. This is a problem because it setTimeoutwill cause evala global scope that does not have access to these variables.

, setTimeout , . , , :

var red = "#FF00000";
setTimeout(function () {
    changeBgColor(red);
}, time);
+7

All Articles