javascript - 重新加载页面后在 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
解决方案
也许像这样
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>
推荐阅读
- reactjs - 无法读取未定义的长度属性
- php - 如何在查询中添加不等于的地方
- angular - 在 Angular 中使用 getElementById 可以吗?
- docker - 如何自动删除在构建过程中创建的旧图像?
- angular - 没有在 Angular 中获得选择选项
- python - 按组计算连续重复
- android - 混淆的 Android 库上的 java.lang.VerifyError
- c++ - 不能在非成员函数中调用成员函数
- ios - 在 iOS swift 中避免单例的最佳方法是什么
- reactjs - 在电子商务 reactjs webapp 上实现购物车的最佳方法