简体   繁体   中英

How I can disable a button in React js for 20 seconds after click

I need disable a button for 20 seconds. When I click, and I get current time, I need that next click could be anable after 20 seconds. I try useeffect, but it didin't work for me.

function App() {
const [time, setTime] = useState([]);
const [endTime, setEndTime] = useState([]);

const startWork = (e) => {
    e.preventDefault();
    const StartTime = {
        thisTime: new Date().toLocaleString(),
    };

    setTime(StartTime);
};

const finishWork = (e) => {
    e.preventDefault();
    const StopTime = {
        endTime: new Date().toLocaleString(),
    };

    setEndTime(StopTime);
};

return (
    <div className='App'>
        <div className='startWork'>
            <h1>Start: {time.thisTime}</h1>
            <button type='button' onClick={startWork} disabled={time.thisTime}>
                Start work
            </button>
        </div>
        <div className='finishWork' />
        <h1>Finish: {endTime.endTime}</h1>
        <button type='button' onClick={finishWork} disabled={endTime.endTime}>
            Finish work
        </button>
    </div>
);

}

Just use a setTimeout in your onClick handler

const [disabled, setDisabled] = useState(false);
...
onClick={() => {e.preventDefault();
    setDisabled(true);
    setTimeout(() => {
        setDisabled(false);
    }, 20000)}
};
...
<button disabled={disabled} />

Try using this concept of Vanilla JavaScript! I had implemented for 3sec but similarly it can be implemented for 20sec .

 let button = document.getElementById('btn'); const wait_20sec = () =>{ setTimeout(function(){ button.setAttribute('disabled', true); }, 3000);//3000ms = 3sec } button.addEventListener('click',wait_20sec)
 <button id="btn">Click Me</button>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM