useCountDown (React Hooks)倒计时

javascript 复制代码
import { useState, useRef } from "react";
import "./styles.css";

/**********************************************************
 * 补全 useCountDown (React Hooks)倒计时的功能
 **********************************************************/

// 请补全,返回:
// count     当前剩余秒数
// start()   开始
// reset()   重置
// isRunning 是否在运行
function useCountDown(options) {
  const {
    total, // 总秒数
    onEnd, // 倒计时结束回调
  } = options;

  const [count, setCount] = useState(total);
  const countRef = useRef(total);

  const [isRunning, setIsRunning] = useState(false);

  const start = () => {
    reset();
    const updateCount = () => {
      if (countRef.current <= 0) {
        setIsRunning(false);
        onEnd();
        clearInterval(timer);
        return;
      }

      setIsRunning(true);
      setCount((count) => count - 1);
      countRef.current--;
    };

    updateCount();
    const timer = setInterval(() => {
      updateCount();
    }, 1000);
  };

  const reset = () => {
    setCount(total);
    countRef.current = total;
  };

  return {
    count,
    start,
    isRunning,
  };
}

// 使用示例
function SmsButton() {
  const { count, start, isRunning } = useCountDown({
    total: 6,
    onEnd: () => console.log("可以重新发送了"),
  });

  return (
    <button disabled={isRunning} onClick={start}>
      {isRunning ? `${count}s 后重试` : "发送验证码"}
    </button>
  );
}

export default function App() {
  return (
    <div className="App">
      <SmsButton />
    </div>
  );
}

演示:

倒计时发送验证码

注意点

  1. 闭包问题,需要使用setCount((count) => count - 1);函数式更新状态,使用ref获取最新count
  2. 计时器需要清理,避免内存泄漏
相关推荐
zzzzzz3105 小时前
react-bits:酷炫动效之外,React 组件库还能提供什么
javascript·react.js·动效
web打印社区12 小时前
网页静默打印热敏小票:从 HTML 到出纸的完整指南
前端·javascript·vue.js·electron·pdf·html
剪刀石头布啊13 小时前
设计一个多计时任务的任务管理功能
前端
ModyQyW14 小时前
vite-plugin-uni-manifest 更新了什么
前端·typescript·uni-app
Asize15 小时前
AI 协作开发新范式:我用 SDD 做了个排版 npm 包
前端·人工智能
kyriewen16 小时前
我把今年流传的前端 AI 面试题整理了一遍——4 类场景题+回答框架(附速查表)
前端·面试·程序员
计算机魔术师17 小时前
国产多模态模型正面硬刚Opus旗舰:差距从30%缩到3%
前端
风骏时光牛马17 小时前
程序员进阶:深度思考,解锁职场成长的底层逻辑
前端
IT_陈寒17 小时前
用了Proxy才发现以前的JavaScript白写了
前端·人工智能·后端
爱丶不疚17 小时前
Eval: Agent 说的 Eval 是什么?从单测、TDD 到 Sentry 聊起
前端·ai编程·vibecoding