sms-lock.js 1.4 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576
  1. /**
  2. * 短信倒计时锁
  3. */
  4. class SmsLock {
  5. // 发送倒计时默认60秒
  6. time = null
  7. // 计时器
  8. timer = null
  9. // 倒计时默认60秒
  10. lockTime = 60
  11. // 锁标记名称
  12. lockName = ''
  13. /**
  14. * 实例化构造方法
  15. *
  16. * @param {String} purpose 唯一标识
  17. * @param {Number} time
  18. */
  19. constructor(purpose, lockTime = 60) {
  20. this.lockTime = lockTime
  21. this.lockName = `SMSLOCK_${purpose}`
  22. this.init()
  23. }
  24. // 开始计时
  25. start(time = null) {
  26. this.time = time == null || time >= this.lockTime ? this.lockTime : time
  27. this.clearInterval()
  28. this.timer = setInterval(() => {
  29. if (this.time == 0) {
  30. this.clearInterval()
  31. this.time = null
  32. localStorage.removeItem(this.lockName)
  33. return
  34. }
  35. this.time--
  36. // 设置本地缓存
  37. localStorage.setItem(this.lockName, this.getTime() + this.time)
  38. }, 1000)
  39. }
  40. // 页面刷新初始化
  41. init() {
  42. let result = localStorage.getItem(this.lockName)
  43. if (result == null) return
  44. let time = result - this.getTime()
  45. if (time > 0) {
  46. this.start(time)
  47. } else {
  48. localStorage.removeItem(this.lockName)
  49. }
  50. }
  51. // 获取当前时间
  52. getTime() {
  53. return Math.floor(new Date().getTime() / 1000)
  54. }
  55. // 清除计时器
  56. clearInterval() {
  57. clearInterval(this.timer)
  58. }
  59. }
  60. export default SmsLock