I've been trying to make a stopwatch in react and redux. I've been having trouble trouble figuring out how to design such a thing in redux.
The first thing that came to mind was having a START_TIMER
action which would set the initial offset
value. Right after that, I use setInterval
to fire off a TICK
action over and over again that calculates how much time has passed by using the offset, adds it to the current time, and then updates the offset
.
This approach seems to work, but I'm not sure how I would clear the interval to stop it. Also, it seems like this design is poor and there is probably a better way to do it.
Here is a full JSFiddle that has the START_TIMER
functionality working. If you just want to see what my reducer looks like right now, here it is:
const initialState = {
isOn: false,
time: 0
};
const timer = (state = initialState, action) => {
switch (action.type) {
case 'START_TIMER':
return {
...state,
isOn: true,
offset: action.offset
};
case 'STOP_TIMER':
return {
...state,
isOn: false
};
case 'TICK':
return {
...state,
time: state.time + (action.time - state.offset),
offset: action.time
};
default:
return state;
}
}
I would really appreciate any help.