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>
);
}
CodePudding user response:
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} />
CodePudding user response:
You can use setTimeout
to control the clickability for the desired duration.
function App() {
const [disabled,setdisabled] = useState(false)
const [endTime, setEndTime] = useState([]);
function clickHandler(){
setdisabled(true)
setTimeout(()=>{setdisabled(false)},20000)
}
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={clickHandler} disabled={disabled}>
Start work
</button>
</div>
<div className='finishWork' />
<h1>Finish: {endTime.endTime}</h1>
<button type='button' onClick={finishWork} disabled={endTime.endTime}>
Finish work
</button>
</div>
);
}
CodePudding user response:
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>
<iframe name="sif1" sandbox="allow-forms allow-modals allow-scripts" frameborder="0"></iframe>