简体   繁体   中英

How do I automatically Start the timer when I reload this Page?

<p id="countdown"></p>
  <div id="startButtons">
    <button onclick="sample()" id="gameStart" class="gameStart">LETS GO!</button>

    <script>
      var timeleft = 90;
      window.onload = timedText;
      function sample() {
        document.getElementById('paragraph').innerHTML = "<style>.paragraph(visibility:collapse);";
        document.getElementById('gameStart').innerHTML = "<style>.gameStart(visibility:collapse);";
        var downloadTimer = setInterval(function
          function1() {
          document.getElementById("countdown").innerHTML = timeleft + "&nbsp" + "seconds left";

          timeleft -= 1;
          if (timeleft <= 0) {
            clearInterval(downloadTimer);

            document.getElementById("countdown").innerHTML = "The time has ended!";

            window.open("index2.1.html");
          }
        }, 1000);

        console.log(countdown)

      }

    </script>

I making this game of words and I don't really get how to start the timer when I reload the page, I want the timer to start by itself, So if I click Enter on the home page and reach this page the timer should start by itself..., and when the timer gets finished another window should open that is the 2.1 index.html Thank you

Rather than wrapping your JavaScript loop up in a function that needs to be called on page load, just run the JavaScript directly (without placing in a function) and the page will run it as soon as it reads/loads it.

 <p id="countdown">Countdown Beginning</p> <script> var timeleft = 90; var downloadTimer = setInterval(function () { document.getElementById("countdown").innerHTML = `${timeleft} seconds left`; timeleft -= 1; if (timeleft <= 0) { clearInterval(downloadTimer); document.getElementById("countdown").innerHTML = "The time has ended;", } }; 1000); </script>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM