Javascript Animations
JavaScript provides the following two functions to be frequently used in animation programs.

1. setTimeout( function, duration)

2. setInterval(function, duration)

3. clearTimeout(setTimeout_variable)

JavaScript can also set a number of attributes of a DOM object including its position on the screen. 
Javascript Animation :

JavaScript animations are done by programming gradual changes in an element's style.

The changes are called by a timer. When the timer interval is small, the animation looks continuous.

<html>
<head>
<title>JS Animations</title>
</head>
<style>
.main_circle {  
width: 300px; 
height: 300px; 
border:2px solid #000;  
border-radius:150px;  
position: relative; 
background:#F2F2F2;
}
#animate {
width: 50px;
height: 50px;  
border-radius:150px; 
position: absolute; 
background-color: #0099da;
}
.my_btn{ 
background:#0099da; 
border-radius:2px; 
padding:6px 20px;
margin:15px 70px; 
color:#FFF;
}
.my_btn:hover{ background:#069;}
</style>
<body>
 
<div class="main_circle">
<div id ="animate"></div>
</div>
 
<script type="text/javascript">
function myMove() {
  var elem = document.getElementById("animate");   
  var pos = 0;
  var id = setInterval(frame, 5);
  function frame() {
    if (pos == 250) {
      clearInterval(id);
    } else {
      pos++; 
      elem.style.top = pos + 'px'; 
      elem.style.left = pos + 'px'; 
    }
  }
}
</script>
 
<button onclick="myMove()" class="my_btn">Start Animation</button>
 
</body>
</html>
Output :
Example 2 :

The moveRight() function is calling setTimeout() function to set the position of imgObj.

We have added a new function stop() to clear the timer set by setTimeout() function and to set the object at its initial position.

<html>
<head>
<title>JS Animations</title>
</head>
 
<style type="text/css">
.my_btn_1{ background:#0099da; border-radius:2px; padding:6px 20px; margin:15px 10px; color:#FFF;}
.my_btn_1:hover{ background:#069;}
</style>
 
 
<script type="text/javascript">
 <!--
var imgObj = null;
var animate ;
 
function init(){
  imgObj = document.getElementById('myImage');
  imgObj.style.position= 'relative'; 
  imgObj.style.left = '0px'; 
}
 
function moveRight(){
  imgObj.style.left = parseInt(imgObj.style.left) + 10 + 'px';
  animate = setTimeout(moveRight,20); // call moveRight in 20msec
}
 
 
function stop(){
  clearTimeout(animate);
  imgObj.style.left = '0px'; 
}
 
window.onload =init;
 //-->
</script>
      
   
<body>
 
  <form>
     <img id="myImage" src="images/Free-Time-Learning-circle.png" width="100" height="90" /><br />
     <input type="button" value="Start" class="my_btn_1" onclick="moveRight();" />
     <input type="button" value="Stop" class="my_btn_1" onclick="stop();" />
  </form>
  
</body>
</html>
Output :