Creating a progress bar feature using local storage in JavaScript

Is there a way to retain the progress of the countdown timer with a progress bar on page reload? Here is an example of what I am trying to achieve: https://codepen.io/Rudchyk/pen/qNOEGj

<div id="progressBar">
                <div class="bar"></div>
            </div>
            <script src="https://code.jquery.com/jquery-2.2.4.min.js"></script>
            <script>
                var seconds = {$timer_limited->sec}; // 10000
                $(document).ready(function () {
                    function progress(timeleft, timetotal, $element) {
                        
                        var progressBarWidth = timeleft * $element.width() / timetotal;
                       
                        $element.find('div').animate({ width: progressBarWidth }, 500);
                        if(timeleft > 0) {
                            setTimeout(function() {
                                progress(timeleft - 1, timetotal, $element);
                            }, 1000);
                        }
                    };

                    progress(seconds, seconds, $('#progressBar'));
                });
            </script>
            <style>
                #progressBar {
                    width: 100%;
                    height: 4px;
                    background-color: #DDDFE2;
                }
                #progressBar div {
                    height: 100%;
                    line-height: 22px;
                    width: 0;
                    background-color: #D03637;
                }
            </style>

Any suggestions on how to save and restore the progress when the page is reloaded?

Answer №1

function trackTime() {
    var progressBarWidth = remainingTime * $progressBar.width() / totalTime;
    $filler.animate({ width: progressBarWidth }, 500).html(Math.floor(remainingTime/60) + ":"+ remainingTime%60);
    
    remainingTime--
    localStorage.setItem('timeLeft', remainingTime)
    if(remainingTime < 0) {
        clearInterval(timerInterval)
    }
};

const $progressBar = $('#progressBar')
const $filler = $progressBar.find('div')

const totalTime = 600
var remainingTime = localStorage.getItem('timeLeft') ?? totalTime

const timerInterval = setInterval(trackTime, 1000)

I made some adjustments to your code, including renaming variables for clarity. One key addition is the utilization of localStorage to store and retrieve the remaining time information. This ensures that the clock is synchronized even upon page refresh.

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

Using the information retrieved from Google Place Autocomplete and saving it for future reference

I am interested in utilizing the Google API "Place Autocomplete" widget to enhance user experience on my website. The specific widget I have in mind can be found here. My goal is to streamline the process of obtaining property addresses from Real Estate A ...

Rendering user actions instantly in React.js without waiting for server propagation

I am currently developing a shopping list web application where users can toggle items as 'checked' or 'unchecked'. The flow of data in this application is as follows: click on item checkbox --> send database update request --> re-ren ...

Best way to eliminate empty options from dropdown and ensure that required validation is functioning in AngularJS?

My dropdown is populated with owners from the owners data, but it includes an extra blank option. I need to eliminate this blank option. However, when I make the necessary changes to remove it, the required validator stops working properly. <md-input-c ...

Is it possible to create tags in Material UI Autocomplete using events other than just pressing the 'Enter' key?

In my current project, I am utilizing the freesolo Autocomplete feature. My specific requirement is to create tags when input text is followed by commas or spaces. Currently, tags are created on the Enter event by Autocomplete, but I am looking for a way t ...

Using global variables for mocha testing (and babel setup)

Currently, I am developing a library using es6 and transpiling it with babel via webpack and npm. However, I have encountered an issue where my library has a dependency on some code that cannot be modified but is required for my library to function properl ...

Does this information operate on Vue or Node?

I have recently started learning programming and currently working on an HTML project for school. My professor mentioned that we should only use Node.js for this project. However, I am concerned that the function I used below might be Vue instead of Node ...

The Image component in a test within Next.js was not wrapped in an act(...) during an update

After setting up a basic NextJS app with create-next-app and integrating Jest for testing, I encountered an error message stating "An update to Image inside a test was not wrapped in act(...)". The issue seems to be related to the Image component in NextJS ...

Vue.js is limited in its ability to efficiently partition code into easily loadable modules

My current issue: I am facing a challenge with splitting my vue.js code into chunks. Despite trying multiple examples from tutorials, I am unable to successfully separate the components and load them only when necessary. Whenever I attempt to divide the c ...

Running NodeJS scripts with ElectronJS is not possible

Goal I'm facing a challenge with executing my separate scripts located in the project/api folder. Let's take test.js as an example, where I am exporting it using module.exports. When I run my electron window and create a JavaScript file with a f ...

Firebase has flagged the Google Authentication process with a message stating: Entry denied: The request made by this application

I have connected my domain to Firebase authentication and granted authorization for authentication access. If you want to test it out, feel free to visit this link signInWithPopup(auth, provider) .then((result) => { // This provides a Google Acc ...

Unable to pass multiple objects as props in Vue component causing issues

Seeking help on passing multiple props to a component using v-for: <my-component v-for="(item, index) in items"></my-component> The data structure 'items' consists of: items: { 1: { name: "Apple", color: "Red" }, 2: { name: "Ba ...

How can one guide a glTF model in the direction it is pointed using A-frame?

I have a 3D model of my customized robot loaded in an A-frame scene using version 1.0.4. Currently, I am able to rotate the robot along its x, y, z axes, but I am facing an issue where it continues to move in its original direction rather than the one it i ...

Ways to resolve the error message "TypeError: 'setOption' is not a function on type 'MutableRefObject' in React"

CODE export default function EChart({ option, config, resize }) { let chart = useRef(null) let [chartEl, setChartEl] = useState(chart) useEffect(() => { if (resize) { chartEl.resize() } if (!chartEl.cu ...

Differences in HTML animations can be seen when comparing Google Chrome to Microsoft Edge. Looking for a workaround for autoplay to ensure

My intro video animation is facing recording difficulties due to the autoplay policy in Google Chrome. It seems nearly impossible to capture it accurately. If only autoplay could function for an offline HTML file, my issue would be resolved. Unfortunately ...

What could be causing the lack of data to be returned by jQuery.getJSON?

I've come across this method: function getUserName(guid) { var name = "Unknown"; $.getJSON(urlCurrent, { "method" : "get_user_info", "guid" : guid, "auth_token" : temporaryAuthToken }, function(data) { if ...

Group the JSON data in JavaScript by applying a filter

I have a specific json object structure with keys cgi, tag and name, where the cgi key may be repeated in multiple objects. If any cgi has the tag 'revert', then that particular cgi should not be returned. [ { "cgi": "abc-123 ...

Updating the options list of an Autocomplete component post-render: A step-by-step guide

I've encountered an issue with a function that retrieves a JSON array from a URL containing a list of options to be displayed in my Autocomplete component. function DisplayOptions() { async function GetOptions() { options_list = await fetc ...

The variable remains undefined, despite the fact that the code executes correctly in a different location

I'm currently working on a multiplayer game in three js and integrating socket.io for real-time communication. I have all the player characters stored in an array called players on the server side. When each client connects, I send them the list of p ...

What is the best way to remove a specific HTML section using a JavaScript function?

I am struggling to figure out how to remove a specific HTML section using a button that is contained within the section itself. The section I want to delete was initially added by clicking a different button. Although I can successfully add a new section ...

Creating Vue3 Component Instances Dynamically with a Button Click

Working with Vue2 was a breeze: <template> <button :class="type"><slot /></button> </template> <script> export default { name: 'Button', props: [ 'type' ], } </scr ...