setInterval()を使ったアニメーションをご紹介します。一定間隔でアニメーションさせたいときに使います。時間を表示する例を見ていきます。
setInterval()の設定
setInterval(関数, 時間間隔);
デモ
setInterval()を利用して、時間を表示する。
<text id="time" x="50" y="42" font-size="22" fill="navy" text-anchor="middle">00:00:00</text> <script type="text/javascript"> var timeobj = document.getElementById("time").firstChild; setInterval(function() { var now = new Date(); timeobj.data = now.toTimeString().substring(0, 8); }, 100); </script>
setInterval()の解除
setInterval()を止めたい場合の書き方です。
デモ
<text id="time" x="36" y="36" font-size="22" fill="blue" text-anchor="middle">0</text> <g font-size="8" text-anchor="middle"> <g fill="magenta" onclick="start()"> <rect x="10" y="45" width="20" height="10"/> <text x="20" y="62">start</text> </g> <g fill="cyan" onclick="stop()"> <rect x="40" y="45" width="20" height="10"/> <text x="50" y="62">stop</text> </g> </g> <script type="text/javascript"> let timeobj = document.getElementById("time").firstChild; let count = 0; let id = null; let time = 0; let display = true; function start() { if (id == null) { id = setInterval(function() { time++; if (display){ timeobj.data = time; } }, 100); time = 0; display = true; } } function stop() { if (id != null) { clearInterval(id); id = null; } } </script>
まとめ
setInterval()の設定と解除を使ったアニメーションについて書きました。