美文网首页
useTimeout

useTimeout

作者: skoll | 来源:发表于2020-08-14 20:14 被阅读0次
// 由用户触发,在指定时间之后恢复状态,可以用来节流,比如一段时间内只能执行1次函数,避免重复点击触发

import {useState,useRef, useCallback} from 'react'
export default function useTimeout(number,count){
    // number:时间,1000毫秒内只能触发一次事件
    // count:次数,规定时间内可以触发的次数,默认是1次
    // 1000:2 :传入这样的参数意味着1秒内最多可以触发2次这个事件
    const [ready,setReady]=useState(false)
    const timerRef=useRef()
    const countRef=useRef(0)

    const start=useCallback(()=>{
        if(countRef.current<=count){
            setReady(true)
            countRef.current+=1
        }else{
            setReady(false)
        }
        timerRef.current=setTimeout(()=>{
            countRef.current-=1
            if(countRef.count<=count){
                setReady(true)
            }
            // 这样就意味着会重置到0,感觉还是不太准确,想了下又感觉是对的

            // countRef.current=-1
        },number)    
    },[number])

    const stop=useCallback(()=>{
        clearTimeout(timerRef.current)
    },[])
    
    return [ready,start,stop]
}

react-use里面,这个是用来做超时返回true值的

相关文章

  • useTimeout

    react-use里面,这个是用来做超时返回true值的

网友评论

      本文标题:useTimeout

      本文链接:https://www.haomeiwen.com/subject/nisndktx.html