setInterval and clearInterval - Does not stop my timer - javascript

I am creating a countdown timer. In one part of the code, I use setinterval to reduce my variable by 1 for the seconds timer. In this case, the state is set to true, so that the timer is running. Clicking the pause button sets the state to false and the clearInterval is triggered. But then, my timer is still running.
Here's my code:
import React from "react";
import "./App.css";
import { useSelector, useDispatch } from "react-redux";
import { playToggle, reset } from "./actions/indexAction";
function Timer() {
const timer = useSelector((state) => state.timer);
const sessionLength = useSelector((state) => state.sessionLength);
let minutes = sessionLength;
let seconds = 60;
let refreshIntervalID;
const dispatch = useDispatch();
let resetClick = () => {
return dispatch(reset());
};
let timerFunction = () => {
if (timer == true) {
seconds--;
console.log(seconds);
}
};
if (timer == "reset") {
minutes = sessionLength;
seconds = 60;
console.log("Is Reset");
}
if (timer == true) {
console.log("timer is playing");
refreshIntervalID = setInterval(timerFunction, 1000);
} else {
console.log("timer is paused");
clearInterval(refreshIntervalID);
}
return (
<div>
<h1>Minutes: {minutes}</h1>
<h1>Minutes: {seconds}</h1>
<div>
<button onClick={() => dispatch(playToggle())}>PLAY/PAUSE</button>
</div>
<div>
<button onClick={resetClick}>RESET</button>
</div>
</div>
);
}
export default Timer;
I have looked around for answers but no luck,
And, here I tried the stateful version, and still no luck.
The code is as follows:
import React from "react";
import "./App.css";
import { useSelector, useDispatch } from "react-redux";
import { playToggle, reset, play, pause } from "./actions/indexAction";
function Timer() {
const timer = useSelector((state) => state.timer);
const sessionLength = useSelector((state) => state.sessionLength);
let minutes = sessionLength;
let seconds = 60;
var refreshIntervalID;
const dispatch = useDispatch();
let resetClick = () => {
return dispatch(reset());
};
let timerFunction = () => {
if (timer == true) {
seconds--;
console.log(seconds);
}
};
if (timer == "reset") {
minutes = sessionLength;
seconds = 60;
console.log("Is Reset");
}
if (timer == true) {
console.log("timer is playing");
refreshIntervalID = dispatch(play());
console.log(refreshIntervalID);
} else {
clearInterval(dispatch(pause()));
}
return (
<div>
<h1>Minutes: {minutes}</h1>
<h1>Minutes: {seconds}</h1>
<div>
<button onClick={() => dispatch(playToggle())}>PLAY/PAUSE</button>
</div>
<div>
<button onClick={resetClick}>RESET</button>
</div>
</div>
);
}
export default Timer;
Please help me on this one.
Thanks!

try to check your refreshIntervalID before assign with new value
if (timer == true) {
console.log("timer is playing");
if(!refreshIntervalID) {
refreshIntervalID = setInterval(timerFunction, 1000);
}
} else {
console.log("timer is paused");
clearInterval(refreshIntervalID);
refreshIntervalID = null;
}
if you want to stop the timer, just set refreshIntervalID to null

Related

How to update variable passed into arrow function after component being rendered

I'm trying to build pomodoro clock (25+5).
I have an arrow function in the child component which takes two variabels: session (passed from parent, in seconds) and Boolean var.
Problem is the function always stays at 1500 seconds even after i modified session in the parent component.
It still passing the updated variable in the child but function always shows 25mins, cant find what am i doing wrong here.
The countdown itself works fine, i just need to figure out how to change amount of time passed in that function (called Countdown in the child component)
Child component:
import React, {useState, useEffect} from "react";
const Countdown = (Session, isStarted) => { // In this function Session is always 25 mins even after if i modify the state of the variable in the parent
let InitialMinutes = Math.floor(Session / 60);
let InitialSeconds = Session % 60;
const [minutes, setMinutes ] = useState(InitialMinutes);
const [seconds, setSeconds ] = useState(InitialSeconds);
useEffect(()=>{
if (isStarted) {
let myInterval = setInterval(() => {
if (seconds > 0) {
setSeconds(seconds - 1);
}
if (seconds === 0) {
if (minutes === 0) {
clearInterval(myInterval)
} else {
setMinutes(minutes - 1);
setSeconds(59);
}
}
}, 1000)
return ()=> {
clearInterval(myInterval);
};
}}, [minutes, seconds, isStarted]);
return (
<div>
{ minutes === 0 && seconds === 0
? null
: <h1> {minutes}:{seconds < 10 ? `0${seconds}` : seconds}</h1>
}
</div>
)
}
function Timer({session}) {
const [isStarted, setIsStarted] = React.useState(false);
return (
<div className='timer'>
<h3>Session</h3>
{Countdown(session, isStarted)}
<button onClick={() => setIsStarted(true)}>start</button>
<button>stop</button>
<button>{session}</button>
</div>
)
}
export default Timer
Parent component:
function App() {
const [Break, setBreak] = React.useState(5);
const [Session, setSession] = React.useState(1500);
const increaseBreak = () => {
setBreak(prevBreak => prevBreak + 1);
};
const decreaseBreak = () => {
if (Break === 5) return Break
setBreak(prevBreak => prevBreak - 1);
};
const increaseSession = () => {
setSession(prevSession => prevSession + 60);
console.log(Session)
}
const decreaseSession = () => {
return Session === 300? Session : setSession(prevSession => prevSession - 60);
}
const formatTime = time => {
let minutes = Math.floor(time / 60);
let seconds = time % 60;
return (minutes < 10? `0${minutes}` : minutes) + ':' + (seconds < 10? `0${seconds}` : seconds)
}
return (
<div className="App">
<div className="wrapper">
<div className='container'>
<h1>25 + 5 Clock</h1>
<div className='length'>
<div className='break-length'>
<h3>Break length</h3>
<div className='adjust'>
<button onClick={decreaseBreak}>-</button>
<div className='number'>{Break}</div>
<button onClick={increaseBreak} >+</button>
</div>
</div>
<div className='session-length'>
<h3>Session length</h3>
<div className="adjust">
<button onClick={decreaseSession}>-</button>
<div className='number' id='session'>{formatTime(Session)}</div>
<button onClick={increaseSession}>+</button>
</div>
</div>
</div>
<Timer session={Session}/>
</div>
</div>
</div>
);
}
export default App;
The Countdown Component never watched for changes in the session state. I Added a use effect at the top of it and changed your variables to states. Code Below.
const Countdown = (Session, isStarted) => {
console.log(Session);
// In this function Session is always 25 mins even after if i modify the state of the variable in the parent
const [InitialMinutes, setInialMinutes] = useState(Session / 60);
const [InitialSeconds, setInitialSeconds] = useState(Session % 60);
const [minutes, setMinutes] = useState(InitialMinutes);
const [seconds, setSeconds] = useState(InitialSeconds);
useEffect(() => {
setInitialSeconds(Session % 60);
setInialMinutes(Session / 60);
setMinutes(InitialMinutes);
setSeconds(InitialSeconds);
console.log(minutes);
}, [Session]);
useEffect(() => {
if (isStarted) {
let myInterval = setInterval(() => {
if (seconds > 0) {
setSeconds(seconds - 1);
}
if (seconds === 0) {
if (minutes === 0) {
clearInterval(myInterval);
} else {
setMinutes(minutes - 1);
setSeconds(59);
}
}
}, 1000);
return () => {
clearInterval(myInterval);
};
}
}, [minutes, seconds, isStarted]);
return (
<div>
{minutes === 0 && seconds === 0 ? null : (
<h1>
{" "}
{minutes}:{seconds < 10 ? `0${seconds}` : seconds}
</h1>
)}
</div>
);
};
function Timer({ session }) {
const [isStarted, setIsStarted] = React.useState(false);
return (
<div className="timer">
<h3>Session</h3>
{Countdown(session, isStarted)}
<button onClick={() => setIsStarted(true)}>start</button>
<button>stop</button>
<button>{session}</button>
</div>
);
}
export default Timer;

using setInterval to increment variable every second - not updating

Inside my functional component I have defined two hooks started:false and sec:0
let interval = null
const Home = () => {
const [sec, setSec] = useState(0)
const [started, setStarted] = useState(false)
So as the name suggests, every second I want to increment this counter.
I have method called setTimer which should increment my sec every second.
function setTimer() {
console.log(started)
if (!started) {
console.log(started)
setStarted(true);
interval = setInterval(() => {
setSec(sec+1)
console.log("ADDED",sec)
}, 1000)
}
}
But it seems that the sec counter never goes above 1. Is there a reason for this?
You should uses a functional state update, so instead of setSec(sec+1) write setSec(prevSec => prevSec + 1)
See the React Hooks API for reference: https://reactjs.org/docs/hooks-reference.html#usestate
let started = false;
let sec = 0;
let setSec = function(seconds) { sec = seconds; }
let setStarted = function() { started = true; }
function setTimer() {
console.log(started)
if (!started) {
setStarted(true);
console.log(started)
interval = setInterval(() => {
setSec(sec+1)
console.log("ADDED",sec)
}, 1000)
}
}
setTimer();
var setStarted = false;
setSec = 0;
function setTimer() {
console.log(setStarted)
if (!setStarted) {
console.log(setStarted)
setStarted = true;
setInterval(() => {
setSec +=1;
console.log("ADDED",setSec);
}, 1000)
}
}
setTimer();
setInterval has closed over the initial value of your state(sec). Every time you are modifiying it, you are doing setSec(0+1), essentially making it 1. This is the problem of stale state.
You can use useRef to have access to the current value always.
import "./styles.css";
import { useState, useRef } from "react";
export default function App() {
const [sec, setSec] = useState(0);
const [started, setStarted] = useState(false);
let interval = null;
let realSec = useRef(0);
function setTimer() {
console.log(started);
if (!started) {
console.log(started);
setStarted(true);
interval = setInterval(() => {
setSec(realSec.current + 1);
realSec.current++;
console.log("ADDED", sec);
}, 1000);
}
}
return (
<>
<p>{sec}</p>
<button onClick={setTimer}>X</button>
</>
);
}

Fully functioning countdown timer using React hooks only

Here's my code. You can also check it out on Stackblitz:
import React, { useState } from 'react';
const Timer = ({
initialHours = 10,
initialMinutes = 0,
initialSeconds = 0,
}) => {
const [hours, setHours] = useState(initialHours);
const [minutes, setMinutes] = useState(initialMinutes);
const [seconds, setSeconds] = useState(initialSeconds);
let myInterval;
const startTimer = () => {
myInterval = setInterval(() => {
if (seconds > 0) {
setSeconds(seconds - 1);
}
if (seconds === 0) {
if (hours === 0 && minutes === 0) {
clearInterval(myInterval);
} else if (minutes > 0) {
setMinutes(minutes - 1);
setSeconds(59);
} else if (hours > 0) {
setHours(hours - 1);
setMinutes(59);
setSeconds(59);
}
}
}, 1000);
cancelTimer();
};
const cancelTimer = () => {
return () => {
clearInterval(myInterval);
};
};
return (
<div>
<h1 className='timer'>
{hours < 10 && hours !== 0 ? `0${hours}:` : hours >= 10 && `${hours}:`}
{minutes < 10 ? `0${minutes}` : minutes}:
{seconds < 10 ? `0${seconds}` : seconds}
</h1>
<button onClick={startTimer}>START</button>
<button>PAUSE</button>
<button>RESUME</button>
<button onClick={cancelTimer}>CANCEL</button>
</div>
);
};
export default Timer;
I'm having trouble with the START button and this is what it looks like when I click on the START button multiple times:
You'll notice that on the first click the number never continues to go down unless I click on the START button again and again but it would look like a broken slot machine. And if I hit on the CANCEL button, it should stop the timer and reset back to the set time, but it doesn't. I don't know how to solve the problem for this 2 buttons, and much more for the PAUSE and RESUME. I don't know how to make them work, too. Please help.
As suggested by #Felix Kling you can try a different approach, to check why your code is not working check the below code, I've made some changes in your Timer component :
import React, { useState } from 'react';
const Timer = ({
initialHours = 10,
initialMinutes = 0,
initialSeconds = 0,
}) => {
const [time, setTime] = useState({
h: initialHours,
m: initialMinutes,
s: initialSeconds,
});
const [timer, setTimer] = useState(null);
const startTimer = () => {
let myInterval = setInterval(() => {
setTime((time) => {
const updatedTime = { ...time };
if (time.s > 0) {
updatedTime.s--;
}
if (time.s === 0) {
if (time.h === 0 && time.m === 0) {
clearInterval(myInterval);
} else if (time.m > 0) {
updatedTime.m--;
updatedTime.s = 59;
} else if (updatedTime.h > 0) {
updatedTime.h--;
updatedTime.m = 59;
updatedTime.s = 59;
}
}
return updatedTime;
});
}, 1000);
setTimer(myInterval);
};
const pauseTimer = () => {
clearInterval(timer);
};
const cancelTimer = () => {
clearInterval(timer);
setTime({
h: initialHours,
m: initialMinutes,
s: initialSeconds,
});
};
return (
<div>
<h1 className='timer'>
{time.h < 10 && time.h !== 0
? `0${time.h}:`
: time.h >= 10 && `${time.h}:`}
{time.m < 10 ? `0${time.m}` : time.m}:
{time.s < 10 ? `0${time.s}` : time.s}
</h1>
<button onClick={startTimer}>START</button>
<button onClick={pauseTimer}>PAUSE</button>
<button onClick={cancelTimer}>CANCEL</button>
</div>
);
};
export default Timer;
Explanation:
in your startTimer function in the last line you're calling cancelTimer
When you're working with hooks then keep in mind you won't get updated value of state variable until you use function inside a set function like I'm doing in setTime and in that callback, you'll get an updated value as a first parameter
In cancelTimer method you're returning a function you've to call clearInterval also myInterval is undefined in cancelTimer so I've set it's value in state
For more information and other ways check this question

React - get time of long pressing button in seconds

I'm trying to return the number of seconds whilst holding in a button.
eg: "click+ hold, inits -> counts & displays 1, 2, 3, 4, 5 -> leaves button -> resets back to 0"
I've gotten close. It works fine, in my console, but whenever I try to update the state it ends up in an infinite loop.
import React, { useState, useEffect } from "react";
const Emergency = () => {
let counter = 0;
let timerinterval;
const [ms, setMs] = useState(counter);
const timer = start => {
console.log("tick tock");
console.log(start);
if (start === true && counter >= 1) {
timerinterval = setInterval(() => {
counter += 1;
console.log(counter);
setMs(counter); //When I remove this, the infinite loop disappears.
}, [1000]);
} else {
setMs(0);
}
};
const pressingDown = e => {
console.log("start");
e.preventDefault();
counter = 1;
timer(true);
};
const notPressingDown = e => {
console.log("stop");
e.preventDefault();
timer(false);
setMs(0);
clearInterval(timerinterval);
};
return (
<>
<button
onMouseDown={pressingDown}
onMouseUp={notPressingDown}
onTouchStart={pressingDown}
onTouchEnd={notPressingDown}
className="button is-primary mt-3"
>
Emergency
</button>
<br />
Time holding it is.... {ms}
</>
);
};
export default Emergency;
An easy way would be to calculate the time difference between mouseDown and mouseUp, but for the sake of UX, I would like to {ms} to update live as I'm holding the button.
Any suggestions?
Thanks!
There are two problems with your code:
You are not clearing interval. timeInterval is a new variable whenever your component is re-rendered. You need to use ref (const timeInterval = React.useRef(null); ... timeInterval.current = ... ; clearInterval(timeInterval.current);
Also you need to remove counter = 1; from your pressingDowm function, because before each setMs you are incrementing it by one
const Emergency = () => {
let counter = 0;
let timerinterval = React.useRef((null as unknown) as any);
const [ms, setMs] = React.useState(counter);
const timer = (start: any) => {
console.log('tick tock');
console.log(start);
if (start === true && counter >= 1) {
timerinterval.current = setInterval(() => {
console.log(counter);
setMs(counter); //When I remove this, the infinite loop disappears.
counter += 1;
//#ts-ignore
}, [1000]);
} else {
setMs(0);
}
};
const pressingDown = (e: any) => {
console.log('start');
e.preventDefault();
counter = 1;
timer(true);
};
const notPressingDown = (e: any) => {
console.log('stop');
e.preventDefault();
timer(false);
setMs(0);
clearInterval(timerinterval.current);
};
return (
<>
<button
onMouseDown={pressingDown}
onMouseUp={notPressingDown}
onTouchStart={pressingDown}
onTouchEnd={notPressingDown}
className="button is-primary mt-3"
>
Emergency
</button>
<br />
Time holding it is.... {ms}
</>
);
};
This is edited code (with some TypeScript stuff, sorry for that)

How to stop a second React timer from looping back from zero?

I'm trying to build a React component that has two timers. The first one is three seconds, and when it hits zero it says "GO!" then immediately starts the next one, which is a 60 second timer. I got all of this to work, but I can't figure out how to stop the 60 second timer from starting over when it hits zero. Ideally I will be splitting these into two components once I figure this out, but right now I just want to get everything to work properly. Can someone steer me in the right direction here?
import React, { Component } from "react";
import ReactDOM from "react-dom"
class Countdown extends React.Component {
constructor(props) {
super(props);
this.state = { time: {}, seconds: 3 };
this.timer = 0;
this.startTimer = this.startTimer.bind(this);
this.countdown = this.countdown.bind(this);
}
formatSeconds (totalSeconds) {
let seconds = totalSeconds;
let minutes = Math.floor(totalSeconds / 60);
if (seconds < 10) {
seconds = '0' + seconds;
}
if (minutes < 10) {
minutes = '0' + minutes;
}
let obj = {
"minutes": minutes,
"seconds": seconds
};
return obj;
}
componentDidMount() {
let timeLeft = this.formatSeconds(this.state.seconds);
this.setState({ time: timeLeft });
}
startTimer() {
if (this.timer === 0) {
this.timer = setInterval(this.countdown, 1000);
}
}
countdown() {
let seconds = this.state.seconds - 1;
this.setState({
time: this.formatSeconds(seconds),
seconds: seconds
});
if (seconds === 0) {
clearInterval(this.timer);
let element = (
<h2>GO!</h2>
);
ReactDOM.render(
element,
document.getElementById('go')
);
this.state.seconds = 61;
let seconds = this.state.seconds - 1;
this.timer = setInterval(this.countdown, 1000);
this.setState({
time: this.formatSeconds(seconds),
seconds: seconds
});
// how do I stop the second timer from looping?
}
}
render() {
return(
<div className="container">
<div className="row">
<div className="column small-centered medium-6 large-4">
<h2 id="go"></h2>
{this.state.time.seconds}<br />
<button className="button" onClick={this.startTimer}>Start</button>
</div>
</div>
</div>
);
}
}
export default Countdown;
Could you break it out into two countdown functions as follows?
class Countdown extends React.Component {
constructor(props) {
super(props);
this.state = {
countdownSeconds: 3,
roundSeconds: 60
};
this.countdown = this.countdown.bind(this);
this.roundCountdown = this.roundCountdown.bind(this);
this.startTimer = this.startTimer.bind(this);
}
startTimer() {
if(!this.countdownTimer) {
this.countdownTimer = setInterval(this.countdown, 1000);
}
}
countdown() {
const currentSeconds = this.state.countdownSeconds - 1;
this.setState({
countdownSeconds: currentSeconds
});
if(currentSeconds === 0) {
this.roundTimer = setInterval(this.roundCountdown, 1000);
clearInterval(this.countdownTimer);
}
}
roundCountdown() {
const currentSeconds = this.state.roundSeconds - 1;
this.setState({
roundSeconds: currentSeconds
});
if(currentSeconds === 0) {
//do whatever
clearInterval(this.roundTimer);
}
}
}
Edit:
If I understand your other question, to display the appropriate countdown you could maybe do something like
render() {
const { countdownSeconds, roundSeconds } = this.state;
return (
<div>
{countdownSeconds > 0 &&
<span>Counting down...{countdownSeconds}</span>
}
{roundSeconds > 0 && countdownSeconds === 0 &&
<span>Round underway...{roundSeconds}</span>
}
</div>
);
}
Or you could functionalize the rendering of the the timer, i.e.
renderTimer() {
const { countdownSeconds, roundSeconds } = this.state;
if(countdownSeconds > 0) {
return <span>Counting down...{countdownSeconds}</span>;
}
return <span>Round underway...{roundSeconds}</span>;
}
and then:
render() {
return (
<div>
{this.renderTimer()}
</div>
);
}

Categories

Resources