Time Dependent Functions
To create time-dependent functions we will need to create an internal timer to which the program will be able to keep track of the functions. Say you want to create a way to schedule plans and have a program remind you of certain tasks only at certain times. The code will make use of three hooks, useState, useEffect, and useRef. The hook useState will return the current state and then what happens when the page is updated. The hook useEffect is needed to take care of any side effects such as the value changing. The hook useRef persists values between renders. Then we will have two state variables, realTime and counter. realTime is the button to start or stop the timer and the initial state will be set to false. The counter variable is the time interval that is being tracked.
The setInterval method allows us to run a function between every period that is set up. setTimeout only has the function run once after a given interval of time.
import React, { useState, useEffect, useRef } from "react";
const SetTimer = () => {
const [time, setTime] = useState(false);
const [counter, setCounter] = useState(0);
useEffect(() => {
let interval;
if (realTime) {
interval = setInterval(() => {
let currCount = useRef(counter).current;
setCounter(counter => counter + 1);
}, 1000);
} else {
clearInterval(interval);
}
return () => clearInterval(interval);
}, []);
}
Next, we create a function for managing the time, where we can the timer on and off.
const manageTime = () => {
manageTime(!time);
}
Set a reset for the counter.
const reset = () => {
setCounter(0);
}
After we render the timer. Two buttons are created. The first one turns on the clock and the second resets the timer.
<div>
<Button
onClick={() => manageTime()}>
{time ? 'Stop Real-Time': 'Start Real-Time'}
</Button>
<Button
onClick={() => reset()}>
Reset Counter
</Button>
</div>
In the future, we can have instances as well where we can have the timer only reach a limit ( time ) and then the timer will reset back to zero. With this method, we can have a function start after each set period of time. We can create a method for when a timer reaches, two hours, the counter will then reset the timer back to zero. Let's say you set up a daily task to take your medication every eight hours. When the timer reaches eight hours a function can be created to make an alarm to take your medication, then it will automatically restart itself back to zero.