Is there a way to prevent my timer from resetting whenever I refresh the page?

Hey everyone, I'm new to coding and I could really use some help here. I have this code for a timer but I'm struggling to make it work properly even after refreshing the page. My goal is to keep the timer running smoothly, but I'm not sure what changes or additions need to be made in the code. Any guidance you can provide would be greatly 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>

Answer №1

Begin the timer by storing the current date and time in session storage. Upon page load, compare this stored time with the current time to determine the elapsed duration.

Update:

Illustration:

I have provided an example utilizing parts of your original code, while also refining and organizing it for better comprehension of the intended goal. Instead of employing user input as a countdown mechanism decrementing every second, I integrate the user's input with the current date and time to define when the timer should end. This approach allows us to refresh the page at any point and retain knowledge of when the timer should conclude.

It is advised to study and grasp this code rather than merely copying and pasting it into your own project.

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

function start() {
    // Stop any ongoing timers
    stop();

    // Obtain 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 the end date/time
    expires = Date.now() + (userInput * 1000); // Assumes userInput is in seconds
    sessionStorage.setItem("expires", expires);
    runTimer(); 
}

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 remaining"); },
     5: function () { display("notifier", "5 seconds left"); },
     0: function () { display("notifier", "Time's up!"); }
};

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

        // If the specified time has passed
        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;
}

// Resume timer if already set up (page refreshed)
var expires = sessionStorage.getItem("expires");
if (expires > 0) runTimer();
</script>
Enter A Numeric Value: <input type="text" id="userTime" />
<input type="button" value="Start" onclick="start()" />
<input type="button" onclick="stop()" value="Stop"  />
</body>
</html>

Answer №2

Consider clearing the input field after retrieving and saving the value.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

tips for efficiently using keyboard to navigate through tabs in an unordered list

Utilizing unordered lists in this web application. I am looking to implement tab navigation with keyboard functionality. How can I achieve this? The first tab should contain text boxes, and when the user fills out a text box and presses the tab key, they s ...

AngularJS allows for editing elements in an array, but not string objects directly

I am a beginner in AngularJS, currently in the learning phase. Query I want to edit a specific rma from the list. When I click on the edit button and call the controller function updateRma(rma), after selecting rma number 11, my absolute URL is "http://l ...

Preventing autocomplete from filling in empty password fields (React.js)

Once the browser autocompletes my login form, I notice that the password input's value is initially empty. However, when I click on the password field, suddenly the value appears. Additionally, there are several inexplicable events being triggered by ...

Enhance the structure of information retrieved from the API

Recently I sought advice on formatting API data and received some excellent responses. However, I encountered an error when the API lacked data for certain assets: https://i.stack.imgur.com/HgJDd.png Here is an example without the highlighted code: http ...

What is the best way to update my component when the selected value is changed?

Currently, I am facing an issue with my map component. It plots polyline data based on the option selected from the select menu component. The problem arises when I change the value in the select menu and click the play button for the animation. Instead of ...

Working with double quotes within variable in JavaScript

I am currently working on dynamically creating HTML tags using JavaScript. Please take a look at the code snippet below: function getPhotosSuccess(data) { if (data.d.results.length > 0) { var response = data.d.results; var innerht ...

Trouble displaying REACT.jsx in browser

I'm currently learning React and struggling to get it running smoothly. HTML function Person(){ return ( <div class="person"> <h1>Max</h1> <p>Your Age: 28</p> </div> ); } ...

What is preventing me from creating accurate drawings on canvas?

I'm currently working on a paint application and facing an issue. When I place the painting board on the left side of the screen, everything works fine and I can draw without any problems. However, when I move it to the right side of the screen, the m ...

What is the process for creating an HTML file that can automatically save?

I am looking to develop a unique HTML document where users can enter text in text fields, save the file by clicking a button, and ensure that their changes are not lost. It's like what wysiwyg does for HTML documents, but I need it to be integrated di ...

Tips for utilizing process.stdin in Node.js with Javascript?

Currently, I'm developing a Javascript-based poker game that is designed to process standard input in the following manner: https://i.stack.imgur.com/D1u15.png The initial line of input will consist of an integer indicating the total number of playe ...

The onClick event in React/NextJS is not functioning properly when applied to an external component

One dilemma I am facing involves my main page and a button component that I have created to be reused throughout my project. Strangely, when I add the onClick event to the external component, the click event does not seem to work. However, if I create the ...

Having trouble retrieving data from JSON using JavaScript

Hey folks, I need some help with the following code snippet: function retrieveClientIP() { $.getJSON("http://192.168.127.2/getipclient.php?callback=?", function(json) { eval(json.ip); });} This function is used to fetch the IP address of visitors. When i ...

Tips on how to prevent certain classes from being impacted by a hue-rotate filter applied to all elements on a webpage

I am currently in the process of adding a feature that allows users to choose between a dark or light theme, as well as select a specific theme color for the app. The implementation involves using CSS filters such as invert(1) for the dark theme and hue-ro ...

Do you have any queries regarding JavaScript logical operators?

I'm struggling with understanding how the && and || operators work in my code. I created a small program to help myself, but it's just not clicking for me. The idea is that when you click a button, the startGame() function would be triggered. va ...

Chatting with a Discord bot

I am currently working on a Discord bot that will execute specific functions based on the questions asked, most of which are yes or no queries. Upon responding with "yes," a particular function should be performed, while answering "no" would terminate t ...

The attempt to access a Spring Boot webservice using AngularJS and the GET method resulted in a 500 status error, indicating that the operation

I have successfully developed a webservice using springboot and angularjs to download an excel file from the server to my local machine. The URL is being generated correctly, however, I am encountering a 500 error. Below is the code snippet: My Springboot ...

using document references in puppeteer's evaluate/waitFor function

I'm feeling a bit lost when it comes to understanding the document reference in puppeteer's evaluate method. The official documentation shows some code that includes this reference within a waitFor function in a node script. I get that these line ...

Engage with an Express server using a net server in Node.js

I had this unique idea where running a nodejs script would initiate an http (express) server on port 8080 and a regular TCP (net) server on port 1337. When you connect to the TCP server using netcat and send "alert," it triggers the alert() command on a ...

Default behavior in Fullcalendar 6 allows for rendering links on both days of the month and weekdays

Is there a way to customize the rendering of days and weekdays in Fullcalendar React? Currently, they are displayed as links by default (<a>{dayContent}</a>), but I'm looking to have them rendered as <div> or <span>. Any sugges ...

Choose Default Value in Drop-Down List in AngularJS when Page Loads

Within the realm of Angularjs, there exists a DropDown: <select ng-model="category" ng-change="categoryChanged(category)" class="form-control" data-ng-options="category as category.name for category in categories"> <option value="">Se ...