onload, auto refresh reload and setInterval

Posted under » JavaScript on 22 March 2013

To execute a JavaScript function, say sortList, immediately after a page has been loaded once, use onload

 <body onload="sortList()"> 

If you don't want to clutter your body tag, you can put this at the end of your JS, eg.

<script>
window.onload = sortList();
</script>

Let's say you want to refresh the page every 3 seconds. There are several ways to do this. Reload the whole page is one way.

 window.onload = function() {
setTimeout("window.location.reload();", 30000);
    }

There are 3 parts to this.

  1. window.onload - which stays in the memory
  2. setTimeout - timer to repeat
  3. window.location.reload() - same page reload

Most of the time, you do not want to reload the whole page but just the element. Like a watch for example where 1000 is 1 second.

setInterval(myTimer, 1000);

function myTimer() {
  const date = new Date();
  document.getElementById("demo").innerHTML = date.toLocaleTimeString();
  }

To stop the timer, you clearInterval

const myInterval = setInterval(myTimer, 1000);

function myTimer() {
  const date = new Date();
  document.getElementById("demo").innerHTML = date.toLocaleTimeString();
  }

function myStopFunction() {
  clearInterval(myInterval);
  }

web security linux ubuntu python django git Raspberry apache mysql php drupal cake javascript css AWS data