I need to store and update a timestamp in local storage so after one minute the modal will execute each time. I want the modal to appear on refresh only if the time stamp has expired or gone past one minute. One minute duration is just for testing purposes. Goal is to only show a modal once a day to user. Here is what I have so far. It only shows modal on refresh and stores local storage key. But after one minute the modal does not appear on refresh and should. Any help appreciated.
$(document).ready(function() {
function shouldShowModal() {
const lastTimestamp = localStorage.getItem("modalTimestamp");
if (!lastTimestamp) {
return true;
}
const parsedTimestamp = parseInt(lastTimestamp, 10);
let expiryLimit = new Date(parsedTimestamp);
expiryLimit = expiryLimit.setMinutes(expiryLimit.getMinutes() 1);
return new Date() > expiryLimit;
}
if (window.localStorage) {
const currentUser = '<%= current_user %>';
const currentTime = new Date($.now());
if (currentUser && shouldShowModal()) {
swal ({
icon: 'warning',
text: 'Notice text here.',
closeOnClickOutside: false,
button: 'ok'
})
localStorage.setItem('modalTimestamp', currentTime);
}
}
}
Updated working with @Barmar solution:
$(document).ready(function() {
function shouldShowModal() {
const lastTimestamp = localStorage.getItem("modalTimestamp");
if (!lastTimestamp) {
return true;
}
const parsedTimestamp = parseInt(lastTimestamp, 10);
let expiryLimit = new Date(parsedTimestamp);
expiryLimit = expiryLimit.setHours(expiryLimit.getHours() 24);
return new Date() > expiryLimit;
}
if (window.localStorage) {
const currentUser = '<%= current_user %>';
const currentTime = new Date();
if (currentUser && shouldShowModal()) {
swal ({
icon: 'warning',
text: 'Notice text here.',
closeOnClickOutside: false,
button: 'ok'
})
localStorage.setItem('modalTimestamp', currentTime.getTime());
}
}
}
CodePudding user response:
currentTime
is a Date
object, you need to save the numeric timestamp in local storage. So use
localStorage.setItem('modalTimestamp', currentTime.getTime());
I also don't see any need to use $.now()
when setting currentTime
. new Date()
defaults to returning the current time.