Maxim Velichkin Maxim Velichkin - 5 months ago 12
HTML Question

JavaScript - can't make the timer function to be called when the page is loaded

I'm trying to make my simple timer function to be called when the page is loaded. But it doesn't work. I think I made mistake somewhere in the

if else
loop, maby here:
setTimeout(function(tag, sec), 1000);

How can I fix it?



<script>
document.addEventListener('DOMContentLoaded', function(tag, sec) {
tag = "timerPlace";
sec = 3600;

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(tag, sec), 1000);
sec -= 1;
} else {
document.getElementById(tag).innerHTML = "Time is over!";
}

}, false);
</script>

<div id="timerPlace"></div>




Answer

Try this,

javascript

// Code goes here
function saysomething() {
    alert('say something');

}
document.addEventListener('DOMContentLoaded', function(tag, sec) {


    tag = "timerPlace";
    sec = 3600;

    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(tag, sec), 1000);
        setTimeout(saysomething, 1000);
        sec -= 1;
    } else {
        document.getElementById(tag).innerHTML = "Time is over!";
    }

}, false);

HTML

<body>
    <div id="timerPlace"></div>
</body>

or

<script>
  //Timer function
 window.onload = function() {
  myFunction();

}; 


  function myFunction(){

   timer('timerPlace',3600);
  }

  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. -->