Introduction:
To change the text's background color in every half second we use the timeout property like this:
Syntax:
setTimeout("function expression",delaytime)
The delaytime is entered as milliseconds (1 second=1000 millisecond).
Example:
x=setTimeout("fun name()",500);
here 500 is the time in milliseconds equals to half second.
How to change the text's background color every half second in JavaScript?
Download this script and see the result.
Example:
<html>
<head>
<title>ChangeBackgroundColor</title>
</head>
<body bgcolor="#ffffcv">
<font color=purple><h3> Background color:</h3>
Background color of the text is Changing every half second.</font>
<P ID=bgchange align=center >
<font color=navy size=8>
This is my<br />
Favorite Car<br />
</font>
</P>
<SCRIPT LANGUAGE="JavaScript">
function turn_gold()
{
bgchange.style.backgroundColor="gold";
violetTimer=setTimeout("turn_violet()", 200);
}
function turn_violet()
{
bgchange.style.backgroundColor="violet";
goldTimer=setTimeout("turn_gold()", 200);
}
// function turn_blue()
// {
// bgchange.style.backgroundColor="blue";
// pinkTimer=setTimeout("turn_pink()", 500);
// }
// function turn_pink()
// {
// bgchange.style.backgroundColor="pink";
// goldTimer=setTimeout("turn_gold()", 500);
// }
turn_gold();
</Script>
<img src=bigcar.jpg align=middle height=200 width=350 />
</body>
</html>
You can add more functions to change more colors and also increase or decrease the time interval.
Output: Output of the above script is as follows:
Figure 1: Text's background color is gold.
In the above figure text's background color is gold and after half second it will change like as follows:
Figure 2: Text's background color is violet.
Text's background color will be change continuously till the browser is open.