How to run a Javascript Function on Page loading

It is a common necessity that web developers face to run a javascript function at the time of page loading. Here we have got two easy ways to that. The second way can be used to display an animation, if you use your brain to do that.

By Using window.onload

<script type="text/javascript">
    window.onload = initialize();
   function initialize()
  {
      //Code to be implemented at page load
  }
</script>
The method described above is the easiest way to run a javascript function at the time of page load. window.onload is the command that can run any desired function at the time of page load.

By Using setInterval :

<p id="demo"><br /></p>
<button onclick="clearInterval(myVar)">Stop time</button>
<script>
var d = 10;
var myVar = setInterval(myTimer, 1000);
function myTimer()
   {
    document.getElementById("demo").innerHTML = d ;
    d = d-1;
    if (d==0)  {clearInterval(myVar);}
   }
</script>
In the above script myvar is a variable declared inside the script, which initializes and calls a function using setInterval. It runs the function mytimer again and again after every 1000 milliseconds (i.e. 1 second). It is a good way to run an animation at the time of page loading. In the above script a countdown from 10 to 1 is displayed, which either stops after reaching 1 or when the user click the button Stop Time.
Share this Article :
Email

No comments:

Post a Comment