How do i pop message and set expire time to that message state stored in local storage?

时间:2017-07-12 08:04:12

标签: javascript local-storage

if(localStorage.getItem('popState') != 'shown'){
        $(function () {
            $('[data-toggle="popover"]').popover({
            content : "....."
        });
          $('[data-toggle="popover"]').popover('show');
        });
            localStorage.setItem('popState','shown')
}

I am using the method above to display popup message to user during page load, and disable the popup message to be displayed after load for second time. How can i make it auto pop out to the user after certain period of time? e.g. after user close the popup message then it will be displayed automatically after an hour.

1 个答案:

答案 0 :(得分:1)

您可以使用以下间隔:

const showPopup = function showPopup() {
  const lastShown = localStorage.getItem('popStateLastShown');
  const hasOneHourPassed = lastShown ?
    (Math.abs(new Date(lastShown) - new Date()) / 36e5) >= 1 :
    false;

  if (hasOneHourPassed || localStorage.getItem('popState') !== 'shown') {
    // Show popup

    localStorage.setItem('popState', 'shown');
    localStorage.setItem('popStateLastShown', new Date());
  }
};

// Run code immediately.
showPopup();

// Check again after an hour.
setInterval(showPopup, 36e5);