How Can I make my timer not reset every time I refresh the page

时间:2018-02-03 10:09:36

标签: javascript

Hello this is my Code I'm just a beginner in coding and I don't really have an Idea how I will finish this. My goal is to keep my timer working even I'll refresh the page but I don't know how to do it. I don't know what codes I should add.Any help would be appreciated.

<html>
<body>
<div id="countdown"></div>
<div id="notifier"></div>
<script type="text/javascript">
    var t;
    function cdpause(){
      clearTimeout(t);
      document.getElementById("notifier").innerHTML = " " ;
}

  function startTimer() {
      clearTimeout(t);
      document.getElementById("notifier").innerHTML = " " ;
      userInput = document.getElementById('userTime').value;

    if(userInput.length == 0){
        alert("Please enter a value");
    } else {
    var numericExpression = /^[0-9]+$/;
    if(!userInput.match(numericExpression)){
    alert("Please enter a number")
    } else {

   function display( notifier, str ) {
    document.getElementById(notifier).innerHTML = str;
  }

    function toMinuteAndSecond( x ) {
    return Math.floor(x/60) + ":" + x%60;
  }

  function setTimer( remain, actions ) {
    (function countdown() {
       display("countdown", toMinuteAndSecond(remain));         
       actions[remain] && actions[remain]();
       (remain -= 1) >= 0
       if(remain==-1){

       }
       else {
       t = setTimeout(arguments.callee, 1000);
       }
    })();
  }


  setTimer(userInput, { 
    10: function () { display("notifier", "Just 10 seconds to go"); },
     5: function () { display("notifier", "5 seconds left");        },
     0: function () { display("notifier", "Time is up");       }
  }
  )}; 
}  
}

</script>
Please Enter A Number: <input type="text" id="userTime" />
<input type="button" value="Go" onclick="startTimer()" />
<input type="button" onclick="cdpause()" value="Stop it"  />
</body>
</html>

2 个答案:

答案 0 :(得分:0)

When starting the timer, you could store the current date/time in session storage and then when the page loads compare the stored time with the current time to work out how long has elapsed.

Edit:

Example:

I have added an example using some of your original code, but also made some edits and tidied some stuff up so that I could wrap my head around what you were trying to achieve. Instead of using the users input as a counter and decrementing every second, I add the users input onto the current date/time to store when the timer should end and then use that to calculate the remaining time; this means we can refresh the page at any point and still know the desired end time of the timer.

Obviously, I recommend studying this code and understanding what it is doing rather than just copying+pasting it into your project.

<html>
<body>
<div id="countdown"></div>
<div id="notifier"></div>
<script type="text/javascript">
var interval;

function start() {
    // If a timer is already running, stop it
    stop();

    // Get and validate user input
    var userInput = document.getElementById('userTime').value;
    if (userInput.length == 0) {
        return alert("Please enter a value");
    }
    var numericExpression = /^[0-9]+$/
    if (!userInput.match(numericExpression)) {
        return alert("Please enter a number");
    }

    // Calculate end date/time
    expires = Date.now() + (userInput * 1000); // Assumes userInput is in seconds
    sessionStorage.setItem("expires", expires);
    runTimer(); // Start the actual timer
}

function stop() {
    if (interval) {
        clearInterval(interval);
        interval = null;
    }
    expires = 0;
    sessionStorage.setItem("expires", expires);

    // Clear the display
    display("notifier", " ");
}

var actions = {
    10: function () { display("notifier", "Just 10 seconds to go"); },
     5: function () { display("notifier", "5 seconds left"); },
     0: function () { display("notifier", "Time is up"); }
};

function runTimer() {
    interval = setInterval(function() {
        var remain = Math.floor((expires - Date.now()) / 1000);

        // If expired time come and gone
        if (remain < 0) {
            clearInterval(interval);
            interval = null;
            return;
        }

        display("countdown", toMinuteAndSecond(remain));
        actions[remain] && actions[remain]();
    }, 1000);
}

function display( notifier, str ) {
    document.getElementById(notifier).innerHTML = str;
}

function toMinuteAndSecond( x ) {
    return Math.floor(x/60) + ":" + x%60;
}

// If a timer is already setup (page has been refreshed) continue it
var expires = sessionStorage.getItem("expires");
if (expires > 0) runTimer();
</script>
Please Enter A Number: <input type="text" id="userTime" />
<input type="button" value="Go" onclick="start()" />
<input type="button" onclick="stop()" value="Stop it"  />
</body>
</html>

答案 1 :(得分:0)

try emptiying the input after the reading of the value and storing it

相关问题