Skip to content
Advertisement

Javascrip count down timer: prevent reseting on page reload

I have a minute timer which counts from 15 to 0. I don’t want to reset (= restart) the timer on page reload. but I can’t figure out how to prevent the timer from resetting on a page reload. I’m using javascript with php. I have tried to add the timer time on load to php session but that didn’t work for me. any suggestions? thank you 🙂

JavaScript
JavaScript

Advertisement

Answer

You could use the localStorage (sessionStorage is also an option but more prone to restart your timer if the user e.g. reconnects in a new tab or restarts the browser)
How to do it to be on the save side (crashes, unexpected bahaviour e.g.you should update the elapsed time in your local storage from time to time. The “normal” situations are handled by checking for the respective event:

JavaScript

EDIT If you want that an elapsed timer is valid for lets say 24 hours you have also to place MY_NEW_SESSION_VAR which is a Date.now() converted in hours when reloading you check against TODAY_DATETIME_IN_HOURS which is a Date.now() converted in hours (This was my use case, if you do not need it just leave it out)

The keys and the values are always strings (note that, as with objects, integer keys will be automatically converted to strings).
When starting your program (loading js) you should check for the vars with:

JavaScript

To delete a single item

JavaScript

If you want to use sessionStorage just replace localStorage with sessionStorage
EDIT full code for the OP tested and working as asked

JavaScript

Copy between your script tags or load as *.js file

User contributions licensed under: CC BY-SA
7 People found this is helpful
Advertisement