React and SetInterval (FCC Pomodoro Timer..)

Asked
Active3 hr before
Viewed126 times

9 Answers

timerreact
90%

Change the setInterval callback function to arrow function.,when the setInterval will call the callback function the this will refer to the setInterval object.,Basically - I want the timer method to subtract 1000ms from the total length state until the the length is 0.

Try this.

  timer() {
     setInterval(() => {
        this.tick();
        console.log("tick");
     }, 1000)
  }
class PomTimer extends React.Component {
  constructor(props) {
    super(props)
    this.state = {
      break: 300000,
      length: 1500000,
      clockFace: ''
    }
    this.clockify = this.clockify.bind(this);
    this.timer = this.timer.bind(this);
    this.reset = this.reset.bind(this);
    this.tick = this.tick.bind(this);
  }

  reset() {
    this.setState({
      break: 300000,
      length: 1500000
    })
    this.clockify();
  }

  tick() {
    //console.log("tick: " + this.state.length);
    if (this.state.length > 0) {
      this.setState( (preState) => {
        return {
            length: preState.length - 1000
        }
      })

    } else {

    }
  }

  clockify() {
    let minutes = Math.floor(this.state.length / 60000);
    let seconds = (this.state.length % 60000) / 1000
    this.setState({
      clockFace: `${minutes}:${seconds}`
    })
  }


  timer() {
    setInterval(() => {
      this.tick();
    }, 1000)
  }

  componentDidMount() {
    this.clockify();
  }
  render() {
    return <div>
      <h1>Pomodoro Clock</h1>
      <div id="break-label">
        <div id="break-increment" onClick={this.breakInc}>+</div>
        <p id="break-length">Break Length: {this.state.break / 60000}</p>
        <div id="break-decrement" onClick={this.breakDec}>-</div>
      </div>

      <div id="session-label">
        <div id="session-increment" onClick={this.sessionInc}> + </div>
        <p id="session-length">Session Length {Math.ceil(this.state.length / 60000)} ({this.state.length})</p>
        <div id="session-decrement" onClick={this.sessionDec}> - </div>

      </div>
      <div id="session">

        <p id="time-left"> Session: {this.state.clockFace} </p>
      </div>
      <button onClick={this.clockify}>test</button>
      <button onClick={this.resetTimer}>Reset</button>
      <button onClick={this.timer}>Timer</button>
    </div>
  }
}
ReactDOM.render(<PomTimer />, document.getElementById("react-root"));
#react - root {
   width: 50 % ;
   display: flex;
   margin: auto;
   border: 2 px solid black;
   border - radius: 50 px;
   justify - content: center;

}
body {
   background - color: #1E555C;
  font-family: 'Verdana'
}

#
   break -increment, #break - decrement, #session - increment, #session - decrement {
         cursor: pointer;
         margin: 0 px 5 px;
         border: 1 px solid black;
         border - radius: 5 px;
         width: 20 px;
         height: 20 px;
         text - align: center;
         background - color: #1E777C;
}

# session - label,
         #break - label,
         #session {
            display: flex;
            flex - direction: row;
            justify - content: center;
            padding - top: 50 px;
         }
         #break - length,
         #session - length {
            margin: 0;
         }

         #time - left {
            font - size: 2 rem;
         }
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/16.6.3/umd/react.production.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/16.6.3/umd/react-dom.production.min.js"></script>
<div id="react-root">
load more v
88%

Hi! I recently started learning Hooks in React and wanted to change my old React Project from FCC with Hooks. I’m changing my Pomodoro (25 + 5 ) Clock, however, it doesn’t work as I expected . If you have any advice for my code It would be really great to have ones. My clock working when I paused with start/pause button but when I clicked only once to start it, it goes under minus. … So it doesn’t change from session mode to break mode. I set setInterval with 100mms now to test it for now.,Interval is a side effect an all the side effects in functional components should be handled inside useEffect hook.,Mutations, subscriptions, timers, logging, and other side effects are not allowed inside the main body of a function component (referred to as React’s render phase ). Doing so will lead to confusing bugs and inconsistencies in the UI.

Notice that when you console.log the value of timeLeft in your changeTime function is not changing and because of that it keeps on decrementing.

const changeTime = () => {
   console.log(timeLeft);

   if (timeLeft > 0) {
      ...
   }
}
72%

and attach this to the audio element:,This was a great project to get some more practice with creating custom components and I also learnt quite a bit about how to implement timers.,I couldn't directly access the audio element in my React component to use its methods. To get around this we can use refs. We create a ref variable in the component:

componentWillMount() {
   const scriptTag = document.createElement("script");
   scriptTag.src =
      "https://cdn.freecodecamp.org/testable-projects-fcc/v1/bundle.js";
   scriptTag.async = true;
   document.body.appendChild(scriptTag);
}
65%

Pretag
 Pretag team - issue, fix, solve, resolve
75%

Instantly share code, notes, and snippets.

Pretag
 Pretag team - issue, fix, solve, resolve
40%

timerRunning: false is toggled when the count down <span> is clicked which starts the timer(probably should have made it a button). This gets passed down to <Timer /> to clear setInterval if the timer is already running.,setInterval() is initiated with a variable name runningTimer which gets saved as a timerId,Inside <App /> this.state.cycle gets passed down to <Timer /> as a cycle prop

I will add assets directory to the main directory and put 2 images into it. Then, for better readability I will create a helper function changeSoundAttributes() for toggleSound() which takes care of toggling state and changing image based on current sound state.
I started off by setting src with relative path ../assets/on.png which didn’t work out too well due to the way webpack bundles the app. One way to overcome that is to import the images

import React from 'react';
import logo from './logo.png';
22%

In this 3 part tutorial series, we’re going to build a simple pomodoro timer as a means to compare vanilla JavaScript, jQuery, React, Angular 1, Angular 2 and Vue.,In this tutorial, first we will create a pomodoro timer using vanilla javascript. Then, we will re-create the same pomodoro timer using jQuery.,The differences between libraries/frameworks will get much more interesting in future posts, where we use Angular, React, and Vue to build this same app.

Pretag
 Pretag team - issue, fix, solve, resolve
60%

load more v
48%

See the complete challenge specifics at FCC Pomodoro Clock.,See the Pen React Pomodoro Clock by Lorenzo (@lorepirri) on CodePen.,I can reset the clock for my next pomodoro.

Pretag
 Pretag team - issue, fix, solve, resolve

Other "timer-react" queries related to "React and SetInterval (FCC Pomodoro Timer..)"