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. 计时器需要清理,避免内存泄漏
相关推荐
map_3d_vis36 分钟前
百度地图 Hello World:5 分钟用 JSAPI 4.0 显示一张地图
前端·javascript·地图·百度地图
不要试图纠正别人1 小时前
构建 0 报错,产物体积翻倍:换引擎最容易漏的对账
前端·javascript
恋猫de小郭1 小时前
Android Keep Rules 解读,直接影响 Google Play 上架和曝光
android·前端·flutter
Hilaku1 小时前
面了 30 家公司拿到 2 个 Offer!
前端·javascript·程序员
延晗2 小时前
【从零开始 DeepSeek Harness 插件开发教程】三、从零开发 DeepSeek Harness 插件——完成第一个插件的挂载与运行
前端·人工智能
择势2 小时前
iOS 工程环境绝对隔离实践:开发机的"编不出"生产包
前端
某哈压力大2 小时前
Vue的双向绑定与自定义组件的v-model
前端·面试
CappuccinoRose2 小时前
前端开发交互体系 - 汇总篇
开发语言·前端·javascript·css·html·交互
天天鸭3 小时前
前端转全栈,要学会后端看项目的思维
前端·后端·ai编程
oil欧哟3 小时前
AI Agent 常用操作入门:独立目录、Plan 模式与跨话题交接指南
前端