倒计时刷新页面不会重置时间

 曾经面试给问到了这样的一个题目( 节流倒计时时,刷新页面会怎么样?有什么办法解决? ),后来复习就写了一下这个小demo

<template>
  <div>
    <div>
      {{ countrdown }}
    </div>
    <button @click="fn">{{ countrdown===init ? '点击发送':`${countrdown}重新发送` }}</button>
  </div>
</template>

<script>
export default {
  data() {
    return {
      init: 10,   // 定义一个变量,用来做时间修改,需要和倒计时时间一样
      inters: null, // 定时器
      countrdown: 10 // 倒计时时间
    }
  }, // methods

  created() {
    // 实例化完成后
    const self = this
    if (window.sessionStorage.getItem('X_no_time') == null) {
      console.log('第一次或者又过来一次')
    } else {
      self.countrdown = Number(window.sessionStorage.getItem('X_no_time'))
      // if (!this.countrdown) {
      this.toLoading()
      // }
    }
  },

  methods: {
    toLoading() {
      // 短信验证码发送
      const self = this
      self.inter = setInterval(self.fusn, 1000)
    },
    fusn() {
      const self = this
      self.countrdown--
      console.log(self.countrdown, '1')
      window.sessionStorage.setItem('X_no_time', self.countrdown) // 存入本地
      if (window.sessionStorage.getItem('X_no_time') <= '0') {
        // 等于0时清空
        window.sessionStorage.removeItem('X_no_time')
      }
      if (self.countrdown <= 0) {
        // 小于或者等于0时
        self.countrdown = this.init // 重新赋值,
        // 如果用户在倒计时期间关闭了浏览器下次打开也面会调用created()方法
        clearInterval(self.inter)
      }
    }, // fusn

    fn() {
      if (this.countrdown !== this.init) {
        console.log('点击了,但是倒计时还没结束')
        return
      }
      console.log('倒计时完成了,可以重新发送了')
      this.toLoading()
    }
  }
} // export default
</script>

  • 0
    点赞
  • 7
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值