Reputation: 115
When a user enters time duration ie. 30mins and click on submit button. So the alert should popup after 30mins from when the button was clicked
I'm trying to do in react, which is the best way to perform this. I need the logic, and if someone can share code even that would be helpful
Upvotes: 0
Views: 31
Reputation: 105
TLDR:
You need the setTimeout function. It takes 2 parameters, one is a callback function and one the duration after how many miliseconds the callback function needs to run.
Deteiled:
First we need 2 states:
const [duration, setDuration] = useState("");
const [isLoading, setIsLoading] = useState(false);
Here we have a simple Component:
return (
<div className="App">
<input
type="number"
value={duration}
onChange={(e) => setDuration(e.target.value)}
/>
<button onClick={handleOnClick}>Start</button>
</div>
);
Now we need to define handleOnClick and use setTimeout there:
function handleOnClick() {
if (isLoading || !duration) return;
const n = Number.parseInt(duration, 10);
setIsLoading(true);
setTimeout(() => {
alert("hello");
setDuration("");
setIsLoading(false);
}, n);
}
The isLoading state is there so to force the user to wait until the time is over.
Here you can find an example: https://codesandbox.io/s/settimeout-moumr
Upvotes: 1