Steps to develop a JavaScript countdown timer that resumes counting even after refreshing the page

I've been trying to figure it out with JavaScript and jQuery, but I'm stumped. I want the timer to not reset when the page is refreshed. It's like an auction countdown where it goes from 3,2 and if you refresh, it should pick up where it left off instead of starting over. For other products, it should start counting down from 3 again. Any ideas?

Edit: To clarify my question.

My problem is that I don't know how to save the remaining time when someone refreshes the page so that it continues counting down. For example, if someone refreshes at 21 seconds and they have 30 seconds to make their choice, after refreshing the site, the counter should continue from 21 seconds and not reset back to 30 seconds. No AJAX.

If possible, a hardcoded solution would be preferred. If not possible, then a cookie-based option.

Answer №1

Upon loading the page, you have the option to assign a name to your window. Before naming it, make sure the window does not already have a name.

If the window is unnamed, give it a name and initiate counting at 0. Save the count value in a cookie each time it increments.

If the window already has a name (indicating a page reload), retrieve the count value from the cookie, increment it, and save it back to the cookie.

UPDATE: For example, trigger the initCount() function upon body load. Utilize decrementAndSave function to decrease the count value and store it in a cookie.

var count = 3; // 3 -> 2 -> 1

function getCookie(c_name) {
    var i, x, y, ARRcookies = document.cookie.split(";");
    for (i = 0; i < ARRcookies.length; i++) {
        x = ARRcookies[i].substr(0, ARRcookies[i].indexOf("="));
        y = ARRcookies[i].substr(ARRcookies[i].indexOf("=") + 1);
        x = x.replace(/^\s+|\s+$/g, "");
        if (x == c_name) {
            return unescape(y);
        }
    }
}

function setCookie(c_name, value, exdays) {
    var exdate = new Date();
    exdate.setDate(exdate.getDate() + exdays);
    var c_value = escape(value) + ((exdays == null) ? "" : "; expires=" + exdate.toUTCString());
    document.cookie = c_name + "=" + c_value;
}

function initCount() {
    if (window.name) {
        count = getCookie("count_" + window.name); // keep separate count cookies for each window    
    } else {
        window.name = "w_" + (new Date().getTime());
        count = 3;
        setCookie("count_" + window.name, count, null);
    }
}

function decrementAndSave() {
    count--;
    // separate cookie for each window or tab
    setCookie("count_" + window.name, count, null);
}

Answer №2

Although not flawless, I created a script for a 30-minute countdown with text change in the final seconds. The only glitch is that it displays 30:60 instead of 31:00 when reaching one minute. I haven't resolved this issue yet. While it may not be perfect for your needs, it could guide you in the right direction.

<script>
//add leading zeros
setInterval(function() {
function addZero(i) {
    if (i < 10) {
        i = "0" + i;
    }
    return i;
}
var x = document.getElementById("timer");
var d = new Date();
var s = (d.getSeconds());
var m = (d.getMinutes());
var a = addZero(30 - m);
var b = addZero(60 - m);
var c = (60 - s);
var z = "<span style='color:red;font-size:50px;'>" + "Break" + "</span>";
var v = "<span style='color:black;font-size:24px;'>" + "Break" + "</span>";
//Decide how much should be subtracted from the time
if (m > 30) {
    y = b;
}
else if (m < 30) {
    y = a;
}
//elements for changing text
if (y < 2 && c < 15) {
    q = z;
}
else {
    q = v;
}

var t = y + (":" + addZero(c) + " Till Station " + (q));
x.innerHTML = t;
}, 250);
</script>


<div align="center" id="timer" style='color:black;font-size:24px;' ></div>

Answer №3

When using a countdown, it's important to have an end time set in order for it to be effective. Instead of just subtracting 1 every second, consider implementing a solution like the one below:

let endTime = new Date(2022,5,20,6,30,0); // Time set for June 20th, 2022 at 6:30 AM
let timer = setInterval(function() {
    let now = new Date();
    let timeLeft = Math.max(0, Math.floor((endTime.getTime() - now.getTime()) / 1000));

    let days, hours, minutes, seconds;
    seconds = timeLeft % 60;
    timeLeft = Math.floor(timeLeft / 60);
    minutes = timeLeft % 60;
    timeLeft = Math.floor(timeLeft / 60);
    hours = timeLeft % 24;
    timeLeft = Math.floor(timeLeft / 24);
    days = timeLeft;

    document.getElementById('counter').innerHTML = "Time remaining: " + days + " days, " + hours + " hours, " + minutes + " minutes, " + seconds + " seconds.";

    if (timeLeft == 0) clearInterval(timer);
}, 1000);

Answer №4

     var interval = 90000; //90 seconds

      function initializeTimer() {
        localStorage.endTime = +new Date() + interval;
      }

      if (!localStorage.endTime) {
        initializeTimer();
      }
      function convertMillisecondsToMinutesAndSeconds(millis) {
        var minutes = Math.floor(millis / 60000);
        var seconds = ((millis % 60000) / 1000).toFixed(0);
        return minutes + ":" + (seconds < 10 ? "0" : "") + seconds;
       }
      setInterval(function () {
        var remainingTime = localStorage.endTime - new Date();
        if (remainingTime >= 0) {
          document.getElementById("tooltip").innerText =
            convertMillisecondsToMinutesAndSeconds(remainingTime);
        } else {
          initializeTimer();
        }
      }, 100);

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

Scrolling smoothly with React-Leaflet

In my React-Leaflet project, I am aiming to implement a seamless zoom effect. I am aware that vanilla Leaflet supports this feature, as mentioned in this post, utilizing smoothWheelZoom. However, considering the compatibility issues between vanilla Leafle ...

Troubleshooting focus loss in React input fields within a Datatable component implemented in a

I noticed an issue with my Datatable where the input field loses focus whenever I type a character and define the component inside another component. Surprisingly, when I directly place the component in the datatable, it works perfectly fine. I understand ...

Iterating using a for loop within different functions

I am facing an issue with this project. I am planning to create a function that calculates from two different `for()` loops. The reason behind having 2 separate functions for calculation is because the data used in the calculations are fetched from differe ...

Managing and comparing category IDs in JavaScript to effectively store and render subcategories

My goal is to set the current category ID in a variable, and if the category changes, I want to store that as well. Then, I need to compare both IDs. If they are not equal, I want to set the subcategory to null. However, I am unsure of where my mistake lie ...

Operating a React application in the background

Being a novice in the world of deploying front-end code, I have encountered a challenging situation that requires assistance. I am currently working on a React App that needs to be operated as a background process. However, I'm facing some confusion r ...

Unlocking Bootstrap variables in Vue development (using Vanilla Bootstrap)

What is the best way to customize or theme bootstrap? I have heard that using sass to override bootstrap variables is recommended, but how can I integrate this into the Vue webpack workflow? I tried searching online and found suggestions to edit the vue.c ...

"Make your slides smooth and responsive with the unslick option in slick

Currently implementing the Slick Slider on a WordPress website. The slider is designed to display 3 columns at a screen size of 1024px and above. When the screen size drops below 1024px, the slider adjusts to show 2 columns, and on mobile devices, it swit ...

Effortless navigation between components in React JS with smooth scrolling

I am encountering difficulties with implementing smooth scrolling on my landing page. I have tried utilizing various npm packages such as smooth scrollbar, but unfortunately, it is not working as expected. How can I achieve smooth scrolling functionality ...

Replacing the useEffect hook with @tanstack/react-query

Lately, I made the decision to switch from my useEffect data fetches to react-query. While my useEffect implementation was working flawlessly, I encountered various issues when trying to directly convert my code for react-query. All the examples I found ...

Problems arise when using AngularJS' .run function after navigating to a different page

I have encountered an issue with ngRoute while navigating between pages in my web application. The main login page is called index.html, and the routing is controlled by the main js file. However, I face a problem when trying to use a .run block on a speci ...

Adding labels to a JavaScript chart can be done by using the appropriate methods

https://i.stack.imgur.com/uEgZg.png https://i.stack.imgur.com/y6Jg2.png Hey there! I recently created a chart using the Victory.js framework (check out image 1) and now I'm looking to incorporate labels similar to the ones shown in the second image ab ...

Include an item in a Vuetify model's array of objects

Currently, I am attempting to store the value of a dynamically loaded radio button into an array of objects. These radio buttons serve as options for a set of questions within a form, and my desired output is as follows: [{"question1":{ " ...

Issue: Alert: Middleware for RTK-Query API designated as reducerPath "api" is missing from store configuration even though it has been included

Currently in the process of migrating my application to NextJS, and I'm dealing with the following store configuration. It's a bit messy at the moment, but I plan on cleaning it up and reducing duplicated code once I have everything functioning p ...

Using JavaScript (without jQuery), modify the target of an anchor link based on its text content

I am working with c# code that dynamically generates Anchor tags. I am looking to modify the target attribute of certain anchor tags based on their text. For example, the HTML code generated by the dynamic c# looks like this: <a target='_blank&ap ...

How can Typescript be leveraged to enforce a generic constraint on an interface?

I have defined 2 interface declarations : interface IStore { } interface AnotherInterface { a: number; } Also, there are 2 classes which implement each interface: class StoreImplementation implements IStore { } class AnotherImplementation implement ...

What is preventing me from binding ng-click to my element?

I've encountered an issue where the ng-click event is not activating on my element. Despite using the in-line controller script as shown below, I am unable to trigger my alert. Are there any integration issues that I should be mindful of? What could p ...

The module 'myapp' with the dependency 'chart.js' could not be loaded due to an uncaught error: [$injector:modulerr]

Just starting out with Angular.JS and looking to create a chart using chart.js I've successfully installed chart.js with npm install angular-chart.js --save .state('index.dashboard', { url: "/dashboard", templateUrl ...

Bypass Security Check in Firefox

I am facing issues while trying to automate selenium on a website owned by a third party. When an authentication prompt like this appears in Firefox, Selenium fails: https://i.sstatic.net/VHQB4.png You can see a similar situation when clicking the Displ ...

I'm puzzled about what could be behind this error message Error [ERR_HTTP_HEADERS_SENT], especially since I've only sent the response header once. How can I figure out the cause

Here is a snippet of code from my routes file: router.get('/api/', async function(request, response){ let entries = await Entries.find({}, function(error){ if(error) console.log(error); }); let catArray = []; entrie ...

Issue encountered with Angular template rendering in combination with Node.js

I'm currently working on a small node project and trying to incorporate AngularJS into it. Within my project, I have a partial view that utilizes ng-controller and ng-repeat. Here is the structure of my angular.html page: <!DOCTYPE html> <h ...