How to make timer not to restart after page refresh?
✔ Recommended Answer
The reason the timer is restarting after page refresh is that the countdown time is not being saved anywhere. Each time the page is refreshed, the script starts the countdown from the beginning again.
So if you want your data to remain the same after the refresh, it should be stored in the localStorage
or sessionStorage
of the browser
var spdVal = 1; var cntDown = localStorage.getItem("countdownTime") || 5 * 60 * spdVal + 7; setInterval(function () { var mn, sc, ms; cntDown--; if (cntDown < 0) { return false; } mn = Math.floor((cntDown / spdVal) / 60); mn = (mn < 10 ? '0' + mn : mn); sc = Math.floor((cntDown / spdVal) % 60); sc = (sc < 10 ? '0' + sc : sc); ms = Math.floor(cntDown % spdVal); ms = (ms < 10 ? '0' + ms : ms); var result = mn + ':' + sc; document.getElementById('stopwatch').innerHTML = result; localStorage.setItem("countdownTime", cntDown.toString()); }, spd);
This is how your js should look like,
See line 2 where we are looking in local store if there is any existing value that we can use or default value.See line 15 where are setting the time on each update on screen.
Source: stackoverflow.com
Answered By: Preetham Reddy
javascript// Get the current time
var startTime = new Date().getTime();
// Store the start time in local storage or session storage
localStorage.setItem('timerStartTime', startTime);
- When the timer starts, store the start time in local storage or session storage:
- When the page loads, check if there is a start time stored in local storage or session storage. If there is, use that as the start time for the timer. Otherwise, start the timer as usual:
javascript// Get the stored start time from local storage or session storage
var storedStartTime = localStorage.getItem('timerStartTime');
// If there is a stored start time, use that as the start time for the timer
if (storedStartTime) {
var startTime = parseInt(storedStartTime);
} else {
var startTime = new Date().getTime();
}
// Calculate the elapsed time since the start time
var elapsedTime = new Date().getTime() - startTime;
// Start the timer with the elapsed time
startTimer(elapsedTime);
Note that local storage is persistent across browser sessions, while session storage is only available for the current session. Choose the appropriate one based on your requirements.
Comments
Post a Comment