如何保持Date对象静态并避免更新?

时间:2016-12-10 01:42:49

标签: javascript date

我有点新手所以请耐心等待。每次有人打开新页面时,我都在javascript中创建了一个日期对象。我想节省用户打开页面的时间,并在一天后创建另一个日期对象,以创建倒数计时器,显示从日期1到日期2的时间。

为实现这一目标,我尝试使用.getTime减去两个日期;我想保持第二个日期是静态的,而不是比当前时间提前一天。遗憾的是,即使我将d2(日期2)限制为仅运行一次并存储在变量nextday中的条件,也不会发生这种情况。这是我的JS

$(function (){
localStorage.clear()
var ran = JSON.parse(localStorage.getItem('run'))
d1 = new Date()
var i = 0 

if(!ran){
    i+=1
    d2 = new Date(d1)
    nextday = d2.setHours(d1.getHours()+24)
    console.log(i)
    console.log(typeof(nextday))
    localStorage.setItem('run',JSON.stringify('ran'))
    localStorage.setItem('nextday',JSON.stringify(nextday))
}
console.log(localStorage)
nday = JSON.parse(localStorage.getItem('nextday'))
console.log(nday)
var seconds = (nday - d1.getTime())

console.log(seconds)
console.log(localStorage)
})

2 个答案:

答案 0 :(得分:1)

每次加载页面时,您的脚本都在清除本地存储:

localStorage.clear()

这样可以防止在运行中存储任何内容。删除它。

答案 1 :(得分:1)

在访问本地存储的数据之前,您需要清除localStorage。因此,您的ran变量始终为空。删除对clear()的一次调用,一切都应该正常。

$(function() {
  // localStorage.clear() <= the offending code!
  var ran = JSON.parse(localStorage.getItem('run'))
  d1 = new Date()
  var i = 0

  if (!ran) {
    i += 1
    d2 = new Date(d1)
    nextday = d2.setHours(d1.getHours() + 24)
    console.log(i)
    console.log(typeof(nextday))
    localStorage.setItem('run', JSON.stringify('ran'))
    localStorage.setItem('nextday', JSON.stringify(nextday))
  }
  console.log(localStorage)
  nday = JSON.parse(localStorage.getItem('nextday'))
  console.log(nday)
  var seconds = (nday - d1.getTime())

  console.log(seconds)
  console.log(localStorage)
})
相关问题