localStorage倒计时实现
时间:2021-06-05 18:35:53
收藏:0
阅读:31
思路:
1.点击时创建一个localStorage
2.并开始一个定时器。每次自减1,当定时器归0删除localStorage
3.这个localStorage的数据是创建时的时间戳(或者未来60s的时间戳)
4.然后每次页面进入时,固定一个参数读取这个 localStorage的数据 - 现在的时间戳
5.这时的参数时一个负值,给他添加60s的时间(如果记录的是未来60s的时间戳,就要反过来减,得到的是一个正数,就没有以下的问题)
为什么这里要加60s:第一,两数相减是负值;
第二,假如用户等了59s,退出再进入,获取的现在时间戳是相对于59s之后的,这时页面倒计时从59s开始,这明显荒唐,我们要的是1s,这时就需要60-59,得到我们想要的
// verifyCodeDisable布尔值:控制按钮是否禁用的状态 // time倒计时,默认0 // overtime结束的时间,默认0 // Date.parse(new Date()) / 1000获取现在的时间戳,去除后面三位0 // 生命周期 mounted() { let _this = this uni.getStorage({ key: ‘phone‘, success: function (res) { _this.overtime = res.data } }); console.log("shijian:"+this.overtime) // 判断overtime是否存在,这里是一个时间戳,其实无所谓,不等于0就行 if(this.overtime > 1122772662) { // 得到time为负数 this.time = this.overtime - Date.parse(new Date()) / 1000 if (this.time < 0) { this.time = this.time + 60 // 按钮是否禁用 this.verifyCodeDisable = true this.codedownTime() } } methods: { // 定时器 codedownTime(){ let _this = this const count = setInterval(() => { this.time-- if (this.time <= 0) { clearInterval(count) _this.verifyCodeDisable = false uni.removeStorageSync(‘phone‘) } }, 1000) } // 获取验证码事件 sendVerifyCode() { let _this = this this.verifyCodeDisable = true // 初始时间,60秒 this.time = 60 uni.setStorage({ key: ‘phone‘, data: Date.parse(new Date()) / 1000 }) _this.codedownTime() }
原文:https://www.cnblogs.com/black-eyes/p/14852652.html
评论(0)