<html>
<head>
<script language=JavaScript>
var imagesSelected = new Array(false,false,false);
var noOfImages = 3;
var totalImagesSelected = 0;
function window_onload()
{
setInterval("switchImage()",4000);
}
function switchImage()
{
var imageIndex;
if (totalImagesSelected == noOfImages)
{
for (imageIndex = 0; imageIndex < noOfImages; imageIndex++)
{
imagesSelected[imageIndex] = false;
}
totalImagesSelected = 0;
}
var selectedImage = Math.floor(Math.random() * noOfImages) + 1;
while (imagesSelected[selectedImage - 1] == true)
{
selectedImage = Math.floor(Math.random() * noOfImages) + 1;
}
totalImagesSelected++;
imagesSelected[selectedImage - 1] = true;
document.imgAdvert.src = "AdvertImage" + selectedImage + ".jpg";
}
</script>
</head>
<body onload="window_onload()">
<img src="AdvertImage1.jpg" name="imgAdvert">
</body>
</html>
The final difference between this solution and the example in the chapter is that we set the timer going continuously with setInterval(). So, until the user moves to another page our random display of images will continue.