JavaScript Tutorial JJavaScript Examples CSS Tutorial HTML Tutorial About Us

Animated Butterfly

We can create an animated butterfly that is flapping its wings using the setInterval() method.

In this example, we need to use eight images of a  butterfly that flaps its wings at a different stage.

Name the images files as bfly1.gif, bfly2.gif, bfly3gif, bfly4.gif, bfly5.gif, bfly6.gif, bfly7.gif, bfly8.gif.

We need to load the images starting from image1 till image 8 and then repeat the sequence again at a regular interval set by using the setInterval() method.

Besides that, we declare a global variable i and assign an initial value 0 to it, then use the iteration i+=1 to increase its value one at a time. We reset the value of i back to 0 after its value exceed 9 using the if statement.

We use the following statement to load the images:

var dice = document.getElementById("die");
The full script is as follows:
var i=0

var step;
function start(){

function rolldice(){
if (i<9){
var dice = document.getElementById("die");
function stop()


❮ Previous Lesson Next Lesson ❯

Copyright©2008 Dr.Liew Voon Kiong. All rights reserved |Contact|Privacy Policy