Bits & Bytes

Creating a Simple Javascript Animation Using Recursion

The animation that we create in this example is a simple progress bar. Above, you can see a light gray rectangle with a darker gray rectangle inside it. The darker gray bar is the progress bar that moves from left to right across the screen.

The code for this animation is below. You can copy code into an empty file with a .html extension or just download the HTML file using this link. Just right-click that link and left-click “Save Link As…” and select a location to save it to. Then double-click the file to open it with a browser.

As you can see in the code below, we define two styles: animbkgd and animbar. These are used to create div elements for the background and the progress bar, respectively. The div elements are created inside the body tag near the bottom of the file.

At the bottom of the head section, we have script tags to define the Javascript code section. We begin by defining three variables: qpBkdg, qpBar, and iWidth. The first two are used to refer to background and progress bar div sections and are set inside the Initialize() function. The third variable keeps track of the width of the progress bar.

The animation is started after the page is loaded with code

window.onload = Initialize;

that sets the Initialize() function to be the callback function for when the page loads.

When Initialize() is called, is initializes the two variables and then calls the animation loop function Loop(). The Loop() function updates the width variables and then sets itself to be called again in 20 milliseconds. That is the effect of the call


The setTimeout() function calls a function after a specified period of time. Here, it is set to call Loop() after 20 milliseconds. So, the code creates a recursive loop where Loop() is called every 20 milliseconds to create the animation.

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"

<html xmlns="" xml:lang="en" lang="en">

<title>'s Javascript Recusive Animation Example</title>

<style type="text/css">
#animbkgd {
    width: 480px;
    height: 50px;
    margin: 30px;

#animbar {
    width: 0px;
    height: 20px;
    left: 0px;
    top: 20px;

<script type="text/javascript">
var qpBkdg = null;
var qpBar = null;
var iWidth = 0;

function Loop() { = iWidth+'px';
    iWidth = ((iWidth + 1) % 480);

function Initialize() {
    qpBkdg = document.getElementById('animbkgd');
    qpBar = document.getElementById('animbar');

window.onload = Initialize;


<div id="animbkgd">
    <div id="animbar">


Tags: , , , , , , , , ,

By: Michael Hall

One Response to “Creating a Simple Javascript Animation Using Recursion”

  1. Parijat says:

    How about a termination clause for the loop function? It’s recursive, even though it will no longer animate once it is 480px wide, it will still keep queuing up the event machine with the loop method and not garbage collecting it

Leave a Reply