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

The component name 'Hidden' is not valid for use in JSX

Currently, I'm immersed in a personal project focused on creating a responsive website utilizing Material-UI. In this endeavor, I've leveraged React and kickstarted the project with create-react-app. To enhance the design, I incorporated code fro ...

Create personalized styles for each item within a stack with specific spacing using the @mui library

Is there a way to change both the background color and spacing area when hovering over each item in my list? https://i.stack.imgur.com/87TST.png <Stack spacing={4} divider={<Divider variant={`fullWidth`} orientation={`horizontal`} flexItem/>}> ...

The Vue router-view is mistakenly loading the parent component instead of displaying its own content

Here is a simple route configuration: { path: '/', component: Home, }, This route configuration sets the path to the home page and loads the Home component when the path is '/'. However, I am encountering an issue where the Po ...

How can I resolve the issue of a lengthy link spanning two lines in Internet Explorer, while displaying correctly in other browsers on a Bootstrap navigation

Currently in the process of developing a responsive website with Bootstrap. The navigation buttons at the top are displaying correctly in Chrome, Safari, and Firefox, but in IE, the button labeled "Public Consultation" is wrapping onto two lines. I suspec ...

Setting an if isset statement below can be achieved by checking if the variable

I have included a javascript function below that is designed to display specific messages once a file finishes uploading: function stopImageUpload(success){ var imagename = <?php echo json_encode($imagename); ?>; var result = '& ...

Issue encountered while transforming the data buffer into the video within a Node.js environment

I am attempting to create a buffer from the mp4 video, and then convert that buffer back into the video. The buffer is being generated as follows: const buffer = Buffer.from("Cat.mp4"); console.log(buffer); The output I receive is <Buffer 43 61 74 2e ...

Arranging Text and Images in HTML/CSS to Ensure Optimal Placement When the Window Size Changes

Hello fellow coders! I've recently started diving into the world of website development and I have a query regarding positioning elements and handling window resizing. Can anyone help me out? I'm trying to center an image, a message, and a passw ...

What could be the reason for the empty array returned by the combinationSum function in Javascript?

The combinationSum function is returning an empty resultArr. When checking the ds array with console.log, it shows the correct answer, but for some reason, the final output array ends up being [[],[]]. var combinationSum = function(candidates, target) { ...

Having a hard time finding the perfect styling solution for Material UI

Is there a way for me to customize the styling of Material UI's components in addition to their default rules by injecting my own CSS? I'm unsure how I would go about setting these parameters using the styled-components API. Is this even doable? ...

Automatically compute and convert currency formats using JavaScript

May I ask again? Hopefully you understand. I am looking to automatically calculate with a money format. Here is a demo: https://jsfiddle.net/xp4ky2gg/ This is my code... HTML code <table style="width:100%"> ...

Is it possible to utilize getInitialProps in both _app.js and in individual pages within the application?

I am currently developing my first significant NextJS application. Instead of hardcoding the left navigation data directly into the app, I have set it up to pull in JSON data. This allows me to make minor changes to the site's navigation without havin ...

The ng-repeat function is failing to show any data on the HTML view, instead only displaying a row for each property present

HTML Code: <div ng-repeat="addr in addrShipData"> <input type="radio" name="resp1" ng-checked='true'/> {{addr.addressLine1 +","+addr.addressLine2+", "+addr.city+ ","+addr.state+", "+addr.country+", "+addr.zipCode+","+addr ...

Receiving array data in a Javascript function and storing it within a variable

Hello everyone, please take a look at my code below. I am attempting to pass PHP array values to a JavaScript function. When I run the script, I receive alerts for parameter0=1, parameter1=2, and parameter2=3 separately. What I am trying to achieve is to ...

Having trouble accessing req.user on my Node.js server using Auth0 and Angular

Currently, I am utilizing auth0 for my admin panel's login system and it is functioning smoothly. However, I have encountered an issue in node where 'req.user' is returning as undefined for some unknown reason. This setup is fairly basic; I ...

Unexpected TypeError thrown by a simple react-cube-navigation demonstration

Looking to utilize the react-cube-navigation component, available here. Encountering a TypeError when attempting to run the provided example, React throws an error: TypeError: props.rotateY.to(function (x) { return "scale is not a function. ( ...

Ensure your TypeScript class includes functionality to throw an error if the constructor parameter is passed as undefined

My class has multiple parameters, and a simplified version is displayed below: class data { ID: string; desp: string; constructor(con_ID:string,con_desp:string){ this.ID = con_ID; this.desp = con_desp; } } When I retrieve ...

Substitute regular expressions with several occurrences by their respective capture groups

I am attempting to use JavaScript to extract only the link text from a string and remove the href tags. The expected behavior is as shown below: <a href='www.google.com'>google</a>, <a href='www.bing.com'>bing</a> ...

What is the process for removing a Discord user using Node.js?

I've been working on creating a discord bot using node.js, but I'm facing an issue where nothing happens when I try to use a command. The console doesn't log anything except for the bot coming online. const Prefix = '$'; bot.on(&a ...

Guide on effectively managing props within a single component in React Navigation

When attempting to navigate from my App component to the GamePlay component, I encountered an issue. Here is a snippet of my App.js: import React from 'react'; import { StyleSheet, Text, View, TouchableOpacity } from 'react-native'; imp ...

Retrieve the player's name from the database using jQuery

How can I retrieve the text value from my scores table in the database? Here is an image of my score table: https://i.stack.imgur.com/CUiMw.png The Player_name is stored as Player_id, which is a foreign key from the players' table. While I c ...