首页 > 解决方案 > 重新加载页面后在 setInterval() 上节省时间?

问题描述

我正在制作一个本应作为休息场所的网页,所有 html 元素将在 5 分钟后隐藏并在 30 分钟后再次显示,但目前只需重新加载页面即可绕过此冷却时间。我打算尝试使用 localStorage.setItem(),但我不确定我将如何获得间隔中剩余的时间来保存或更新它。我的代码在这里。

<script>

var body = document.querySelector('body')
    
    setInterval(()=>{
        body.style.display = 'initial' ;
        setTimeout(()=>{
              body.style.display = 'none'
        }, 300000)
     }, 180000)


</script> 
<body>
<h1>example html</h1>

</body

标签: javascripthtmlvariablescookies

解决方案


也许像这样

const body = document.querySelector('body');
const aMinute = 60000;
let d = localStorage.getItem("d"); 
let now = new Date().getTime;
let end = d ? new Date(d) : new Date().getTime();
let tId = setInterval(()=>{
  now = new Date().getTime;
  body.classList.toggle("initial",now-end > 0);
}, 180000)
// some event to set
localStorage.setItem("d",(new Date().getTime()+5*aMinute));
<h1>example html</h1>

推荐阅读