In this article, we will make and learn to make animation using Javascript. JavaScript does not have a function such as Java‟s sleep method that pauses a task for a specified period of time. However, JavaScript has two functions that can be used to delay the execution of a function.
- setTimeout – Will execute a function a specific number of milliseconds in the future
- setInterval – Will execute a function every millisecond
Both functions take on two arguments:
- Function – The first argument identifies the function to execute
- Time – The number of milliseconds
setTimeout(someFunction,500); // The function will be executed 500 milliseconds
setInterval(someFunction,500); // The function will be executed 500 every milliseconds
The use of the setTimeout is illustrated here by moving a tag across the screen. The int function setups the animation by retrieving a reference to the tag and calling the move function. The function move modifies the position of the tag and recursively schedules itself for future invocation.
function move() {
square.style.left = parseInt(square.style.left)+1+'px';
setTimeout(move,20);
}
function init() {
square = document.getElementById('Square');
square.style.left = '0px';
move();
}

The complete page follows:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Javascript Animation</title>
<style>
body{
background-color: black;
}
#Square {
position: absolute;
left: 0px;
top: 8em;
width: 5rem;
height: 5rem;
line-height: 3em;
background: #99ccff;
border: 1px solid #003366;
white-space: nowrap;
padding: 0.5em;
}
</style>
</head>
<body>
<div id="Square">
</div>
<script>
var square = null;
function move() {
square.style.left = parseInt(square.style.left) + 1 + 'px';
setTimeout(move, 20);
}
function init() {
square = document.getElementById('Square');
square.style.left = '0px';
move();
}
window.onload = init;
</script>
</body>
</html>
The same effect can be created using the setInterval function.
function move() {
square.style.left = parseInt(square.style.left)+1+'px';
}
function init() {
square = document.getElementById('Square');
square.style.left = '0px';
setInterval(move,20);
}