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>
source
share