'Trigger an alert after a particular time has passed from the current time when the button was clicked
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
Solution 1:[1]
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
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | Maziar B. |
