Fade-In Complete


Tutorial Table of Contents  |   Back to Script Examples

Here's the script to do the fade-in:
<html> <head> <title>Fade In Script</title> <script language = "JavaScript"> <!-- var timer = 5800; document.bgcolor = "#000000"; for (i=0; i < timer ; i++){} document.bgcolor = "#212121"; for (i=0; i < timer; i++){} document.bgcolor = "#404040"; for (i=0; i < timer; i++){} document.bgcolor = "#616161"; for (i=0; i < timer; i++){} document.bgcolor = "#808080"; for (i=0; i < timer; i++){} document.bgcolor = "#A1A1A1"; for (i=0; i < timer; i++){} document.bgcolor = "#BFBFBF"; for (i=0; i < timer; i++){} document.bgcolor = "#E0E0E0"; for (i=0; i < timer; i++){} document.bgcolor = "#ffffff"; // --> </script> </head> <body> <h2>Fade-In Complete</h2> </body> </html>


This script is fairly simple in construction. It changes the bgcolor property of the document object. (Note: the case usage of "bgcolor" is important, as is always the case when referencing object properties in JavaScript.)

Note that the script is not within a function. Thus, it executes as the document loads into the window. A new background color is loaded after a for loop iterates 5800 times. This number is somewhat random and will have a good effect for fairly quick CPUs (say >120MHz). Anything slower than that and the fade in will be very slow.

A better way to write this script would be to have a non-processor dependent "wait" event between changes in bgcolor. In Perl, for instance, you can use the sleep command and in Java you can use Thread.sleep(). There is no similar function built in to JavaScript.

Using the JavaScript function setTimeout() will not work here, because setTimeout() does not cause the processor to pause and let nothing else execute, thus causing a true wait or sleep. Instead, setTimeout() spawns a new thread, counts the given wait time in the background and then executes at that time. During the wait, however, the current CPU thread is free to continue executing. This is an unfortunate lack of function of JavaScript, but is probably due to security concerns, not oversight.