useInterval

以 Hook 的方式使用 setInterval,并自动处理组件卸载时的定时器清理。

基础用法

import { useInterval } from 'miaoma-rhooks'
import React, { useState } from 'react'

function Counter() {
    const [count, setCount] = useState(0)

    useInterval(() => {
        setCount(count + 1)
    }, 1000) // 每秒执行一次

    return <p>Count: {count}</p>
}

API

useInterval(
  fn: () => void,
  delay?: number | null,
  options?: {
    immediate?: boolean;
  }
): {
  clear: () => void;
};

Params

参数 说明 类型 默认值
fn 要定期执行的函数 () => void -
delay 间隔时间,单位为毫秒。设置为 nullundefined 时会停止计时器 number | null | undefined undefined
options 配置选项 { immediate?: boolean } { immediate: false }

Options

参数 说明 类型 默认值
immediate 是否在首次渲染时立即执行 boolean false

Result

参数 说明 类型
clear 清除当前计时器 () => void

进阶用法

动态调整间隔时间

import { useInterval } from 'miaoma-rhooks'
import React, { useState } from 'react'

function DynamicInterval() {
    const [count, setCount] = useState(0)
    const [delay, setDelay] = useState(1000)

    useInterval(() => {
        setCount(count + 1)
    }, delay)

    return (
        <div>
            <p>Count: {count}</p>
            <p>Delay: {delay}ms</p>
            <button onClick={() => setDelay(delay / 2)}>加速</button>
            <button onClick={() => setDelay(delay * 2)}>减速</button>
        </div>
    )
}

暂停和恢复

import { useInterval } from 'miaoma-rhooks'
import React, { useState } from 'react'

function PausableInterval() {
    const [count, setCount] = useState(0)
    const [running, setRunning] = useState(true)

    useInterval(
        () => {
            setCount(count + 1)
        },
        running ? 1000 : null // 当 running 为 false 时暂停
    )

    return (
        <div>
            <p>Count: {count}</p>
            <button onClick={() => setRunning(!running)}>{running ? '暂停' : '恢复'}</button>
        </div>
    )
}

立即执行

import { useInterval } from 'miaoma-rhooks'
import React, { useState } from 'react'

function ImmediateInterval() {
    const [count, setCount] = useState(0)

    useInterval(
        () => {
            setCount(count + 1)
        },
        1000,
        { immediate: true } // 立即执行一次,然后每秒执行一次
    )

    return <p>Count: {count}</p>
}

手动清除

import { useInterval } from 'miaoma-rhooks'
import React, { useState } from 'react'

function ManualClearInterval() {
    const [count, setCount] = useState(0)

    const { clear } = useInterval(() => {
        setCount(count + 1)
        if (count >= 5) {
            // 达到 5 后自动停止
            clear()
        }
    }, 1000)

    return (
        <div>
            <p>Count: {count}</p>
            <button onClick={clear}>停止</button>
        </div>
    )
}