0

The problem is that the timer doesn't reset after the user has used up the delegated time. It is an online text platform. I have had a timer that started from 25mins and I logged out at about 19mins remaining, since i didn't use up the time. But when I came back almost about 7 hours later, it still has the time of 19mins remaining and counting down.

I have checked this previously asked question: How can I reset the timer after a certain duration?, but did not find what I need. And another one didn't have an answer at all: How do I reset this timer.

var total_seconds = sessionStorage.getItem("timeleft") || 60 * 25;
var c_minutes = parseInt(total_seconds / 60);
var c_seconds = parseInt(total_seconds % 60);

function CheckTime() {
    document.getElementById("time").innerHTML = c_minutes + ':' + c_seconds;
    if (total_seconds <= 0) {
        setTimeout(window.location.href = "dashboard.php");
        sessionStorage.clear("timeleft", total_seconds);
    } else {
        total_seconds = total_seconds - 1;
        c_minutes = parseInt(total_seconds / 60);
        c_seconds = parseInt(total_seconds % 60);
        sessionStorage.setItem("timeleft", total_seconds);
        setTimeout("CheckTime()", 1000);
    }
}
setTimeout("CheckTime()", 1000);

I expect that the timer resets so that when the user wants to take another test, it starts to count from the beginning. Just like a new time. Although I do not want to kill the user session (although even this did not work when I tried it) rather I want the session for time alone to be destroyed somehow.

  • Just set `total_seconds` to a new "initial" value? – Bergi Aug 25 '19 at 19:16
  • 1
    resetting total_seconds keeps timer going. Page closing/reopening will always start anew. You maybe want localStorage if you want a timer to pick up where it left off? It's not clear what the goal is. https://developer.mozilla.org/en-US/docs/Web/API/Window/sessionStorage – Gavin Aug 25 '19 at 19:18
  • Timer picks up where it left off, but after a session closure it still continues, which I do not want – Guy Randalf Aug 26 '19 at 02:07

1 Answers1

0

Update

Sorry I didn't read your question thoroughly enough.

You can include a handler to remove the session value on page change. This should do the trick.

window.onbeforeunload = () => sessionStorage.clear("timeleft");
Proximo
  • 6,235
  • 11
  • 49
  • 67
  • @GuyRandalf updated my answer. You can put this at the beginner or end of your code. – Proximo Aug 26 '19 at 13:48
  • Yeahhhhhh this did the whole stuff 100%, I can't upvote yet :( ... Well is there a way i can secure this with a server side scripting or something so it will not be altered? :) – Guy Randalf Aug 26 '19 at 20:02
  • @GuyRandalf You can mark it as the accepted answer. I recommend asking a separate question about securing your script. – Proximo Aug 28 '19 at 02:11