Retain Settimeout() After Page Refreshes Or Moves To Another Page
I need to show my alert message after 15 minutes, but it doesn't work if the page refreshes or if I change pages. I am doing this on the same web page. When I press a button, it sh
Solution 1:
- Store the initial time in local storage
- Whenever the page loads, compare the value in local storage to the current time and start the timeout again from where you left off.
So something like this (untested):
var waitTime = 900000; // 15 minutesvar executionTime;
var initialTime = localStorage.getItem("initialTime");
if (initialTime === null) {
localStorage.setItem("initialTime", (newDate()).getTime());
executionTime = waitTime;
}
else {
executionTime = parseInt(initialTime, 10) + waitTime - (newDate()).getTime();
if (executionTime < 0) executionTime = 0;
}
setTimeout(function() {
alert("Warning");
// reset the timeout to start from waitTime on page reloadlocalStorage.removeItem("initialTime");
}, executionTime);
Edit:
If you don't want to use localStorage, you could store it in an asp.net session variable like so:
Session["InitialTime"] = (DateTime.UtcNow - New DateTime(1970, 1, 1, 0, 0, 0)).TotalSeconds;
Then do similar logic to the javascript code above and output the result as the second argument in the setTimeout function (but remember to convert seconds to milliseconds for the setTimeout).
Post a Comment for "Retain Settimeout() After Page Refreshes Or Moves To Another Page"