I have successfully created a grid with a button that enables me to control a timer.
When I click on the start button in the grid on the home page, the timer begins counting the time.
By using a service, I am able to determine whether the timer is active or not, and change the status of the button on the navbar component accordingly.
My question is: How can I pause the timer (execute the pauseTimer function) from the home service/component, but trigger it from the navbar component? Essentially, I want to be able to pause a timer that was started on the home page by clicking the stop button on the navbar component.
Any assistance would be greatly appreciated!
UPDATED CODE:
startTimer(userId:string) {
if (!this.timerForUsers[userId]) {
this.timerForUsers = {
...this.timerForUsers,
[userId]: {
currentState: 'start',
currentTime: 0,
initialTime: 0,
startTime: `${Date.now()}`
}
};
}
const currentUserTimer:TimerForUser = this.timerForUsers[userId];
clearInterval(currentUserTimer.interval);
currentUserTimer.startTime = `${Date.now()}`;
currentUserTimer.initialTime = currentUserTimer.currentTime;
currentUserTimer.interval = setInterval(() => {
this.timerForUsers = {
...this.timerForUsers,
[userId]: {
...this.timerForUsers[userId],
currentTime: this.timerForUsers[userId].currentTime + 1
}
};
}, 1000);
this.userID = userId;
currentUserTimer.currentState = 'start';
this.state = currentUserTimer.currentState;
localStorage.setItem('user_timers', JSON.stringify(this.timerForUsers));
}
pauseTimer(userId:string) {
const currentUserTimer:TimerForUser = this.timerForUsers[userId];
currentUserTimer.currentState = 'pause';
this.state = currentUserTimer.currentState;
clearInterval(currentUserTimer.interval);
currentUserTimer.interval = null;
currentUserTimer.initialTime = currentUserTimer.currentTime;
currentUserTimer.startTime = null;
localStorage.setItem('user_timers', JSON.stringify(this.timerForUsers));
currentUserTimer.currentTime = null;
}
gettimes() {
return this.userID;
}
getCurrentState() {
return this.state;
}