-3

How can I make this function (simple timer) to be called after the page is loaded? I really need your advice about the most simple way to do it.

<script>
  //Timer function
function timer(tag, sec) {
  document.getElementById(tag).innerHTML = "<div id= 'inTime'>" +
      (sec / 60 >> 0) + 'min ' + sec % 60 + 'sec' + '<br>' + "</div>";



    if ((sec / 60 >> 0) != 0 || (sec % 60) != 0) {
      setTimeout(function() {
        timer(tag, sec);
      }, 1000);
      sec -= 1;
    } else {
      document.getElementById(tag).innerHTML = "Time is over!";
    }
  }
</script>

<div id="timerPlace"></div>
<br>
<br>
<br>
<br>
<!-- Write number of seconds here: onclick="timer('str',...here!...)  -->

<button class="button" onclick="timer('timerPlace',3600); style.display = 'none'"> <span>Start Test</span> 
</button> 

<!-- Place this div where you whant timer to be. -->
Rumata
  • 1,027
  • 3
  • 16
  • 47

1 Answers1

1

Your question wasn't really that clear, but if I get what you asked, you need to use window.onload=function(){ /*code here*/ } and the code will be executed as soon as the page loads.

<script>
  //Timer function
function timer(tag, sec) {
  document.getElementById(tag).innerHTML = "<div id= 'inTime'>" +
      (sec / 60 >> 0) + 'min ' + sec % 60 + 'sec' + '<br>' + "</div>";



    if ((sec / 60 >> 0) != 0 || (sec % 60) != 0) {
      setTimeout(function() {
        timer(tag, sec);
      }, 1000);
      sec -= 1;
    } else {
      document.getElementById(tag).innerHTML = "Time is over!";
    }
  }
window.onload=function(){
timer('timerPlace',3600);
}
</script>

<div id="timerPlace"></div>
<br>
<br>
<br>
<br>
<!-- Write number of seconds here: onclick="timer('str',...here!...)  -->

<button class="button" onclick="timer('timerPlace',3600); style.display = 'none'"> <span>Start Test</span> 
</button> 

<!-- Place this div where you whant timer to be. -->
Paul Ghiran
  • 1,233
  • 1
  • 16
  • 29
  • Yes, this is just what I was needed! Thank you very much and sorry for confusing explanation. – Rumata Jul 04 '16 at 12:15