一定時間ごと画像を入れ替える

説明

一定時間ごと画像を入れ替えるにはsetIntervalタイマーを使って画像のURLを指定します。入れ替える画像のURLは、あらかじめ配列内に指定しておきます。この配列の何番目の画像を表示するかを示すカウンタを用意します。このカウンタを1ずつ増やして行くことで画像を入れ替えることができます。カウンタが配列の要素数を超えたら0に戻すことで延々と繰り返すことができます。
JavaScriptテクニック ブック  詳しい解説などはJavaScriptテクニック ブックを参照してください。

サンプルコード [実行]

<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
<head>
<meta http-equiv="content-type" content="text/html;charset=utf-8">
<title>JavaScript Sample</title>
<link rel="stylesheet" type="text/css" href="main.css" media="all">
<script type="text/javascript" src="main.js"></script>
</head>
<body>
<h1>一定時間ごと画像を入れ替える</h1>
<div class="photoAlbum">
<img src="images/DSC0001.jpg" id="photo">
</div>
</body>
</html>

window.onload = function(){
setInterval("album.swapImage()", 2000);
}
var album = {
imageURL : [
"images/DSC0001.jpg",
"images/DSC0042.jpg",
"images/DSC0103.jpg",
"images/DSC0154.jpg",
"images/DSC0280.jpg"
],
swapImage : function(){
this.count++;
if (this.count >= this.imageURL.length) this.count = 0;
document.getElementById("photo").src = this.imageURL[this.count];
},
count : 0
};