发送验证码后的节流倒计时丨刷新 & 重新进入页面,还原倒计时状态

前言

  最近在做一个 H5 工具,需要手机号 + 验证码登录,很自然地,点击发送验证码后需要等待一段时间才能重新发送,用于请求节流,避免用户疯狂点击:

  不过这里其实有个隐藏需求------如果仍然在冷却时间内,那么用户无论是刷新或是关闭页面,再次打开登录弹窗,需要直接展示正确的倒计时状态

解决方案

使用经典的 localStorage

  1. 发送验证码时,将发送时间 (lastSendingTime) 存入 localStorage,并开启 60 秒倒计时。
  2. 倒计时结束后,清除 localStorage 中的 lastSendingTime
  3. 重新进入页面时,若 localStorage 中存有 lastSendingTime,则说明仍处于冷却时间内,那么计算出剩余的倒计时 N,并开启 N 秒倒计时。

Talk is cheap, show me the code!

js 复制代码
  const [countdown, setCountdown] = useState(60) // 倒计时
  const [canSendCode, setCanSendCode] = useState(true) // 控制按钮文案的状态
  const [timer, setTimer] = useState() // 定时器 ID

  async function sendVerificationCode() {
    try {
      // network request...
      Toast.show({ content: '验证码发送成功' })
      startCountdown()
      setCanSendCode(false)
    } catch (error) {
      setCountdown(0)
      setCanSendCode(true)
    }
  }

  function startCountdown() {
    const nowTime = new Date().getTime()
    const lastSendingTime = localStorage.getItem('lastSendingTime')
    if (lastSendingTime) {
      // 若 localStorage 中存有 lastSendingTime,则说明仍处于冷却时间内,计算出剩余的 countdown
      const restCountdown = 60 - parseInt(((nowTime - lastSendingTime) / 1000), 10)
      setCountdown(restCountdown <= 0 ? 0 : restCountdown)
    } else {
      // 否则说明冷却时间已结束,则 countdown 为 60s,并将发送时间存入 localStorage
      setCountdown(60)
      localStorage.setItem('lastSendingTime', nowTime)
    }

    setTimer(
      setInterval(() => {
        setCountdown(old => old - 1)
      }, 1000),
    )
  }

  // 重新进入页面时,若 localStorage 中存有上次的发送时间,则说明还处于冷却时间内,则调用函数计算剩余倒计时;
  // 否则什么也不做
  useEffect(() => {
    const lastSendingTime = localStorage.getItem('lastSendingTime') 
    if (lastSendingTime) {
      setCanSendCode(false)
      startCountdown()
    }

    return () => {
      clearInterval(timer)
    }
  }, [])

  
  // 监听倒计时,倒计时结束时:
  // * 清空 localStorage 中存储的上次发送时间
  // * 清除定时器
  // * 重置倒计时
  useEffect(() => {
    if (countdown <= 0) {
      setCanSendCode(true)
      localStorage.removeItem('lastSendingTime')
      clearInterval(timer)
      setCountdown(60)
    }
  }, [countdown])

return (
  {canSendCode ? (
    <span onClick={sendVerificationCode}>
      获取验证码
    </span>
  ) : (
    <span>
      获取验证码({`${countdown}`})
    </span>
  )}
)

最终效果

总结

  一开始感觉这是个很简单的小需求,可能 20min 就写完了,但实际花了两个多小时才把逻辑全部 cover 到,还是不能太自信啊~

相关推荐
不听话坏6 小时前
Ignition篇(下 一) 动态执行前的事情
开发语言·前端·javascript
likeyi076 小时前
require 和 import的区别
开发语言·前端
pany6 小时前
做 AI 友好的开源 Vue3 模板 🌈
前端·vue.js·ai编程
小二·7 小时前
React 19 + Next.js 15 现代前端开发实战:App Router / Server Components / 流式渲染
前端·javascript·react.js
谙忆10248 小时前
前端图片直传对象存储:OSS/S3 预签名 URL、STS 临时凭证与回调校验
前端
CHNE_TAO_EMSM9 小时前
Android studio 打开文件时自动下载源码
前端·javascript·android studio
一孤程10 小时前
Airtest自动化测试第五篇:小程序与Web测试——跨平台自动化全覆盖
前端·自动化测试·小程序·自动化·测试·airtest
IT_陈寒10 小时前
SpringBoot自动配置不是你以为的那样的智能
前端·人工智能·后端
yume_sibai11 小时前
大屏数据可视化 - 边框红绿呼吸灯实现详解
前端·信息可视化·typescript
竹林81811 小时前
从 ethers.js 迁移到 Viem:一个签名验证 Bug 让我彻底放弃旧爱
javascript