How to Clear an Interval in React
Welcome back to the course. In the last video, we got our timer working, but you'll notice that if we change the date to another date: it screws things up by adding a bunch of timers in.
Guide Tasks
  • Read Tutorial
  • Watch Guide Video
Video locked
This video is viewable to users with a Bottega Bootcamp license

Let's get rid of that error by going into our code, and clearing the interval when we hit change date. Let's go to app.js. We have out timer object, and we have this clear interval function here.

large

Now we don't want to put it here, we want to put it in the change date. It says handleChange right here. We need to say:

app.js

  handleChange = function(date) {
    console.log("APP JS HANDLE CHANGE", date._d);
    clearInterval(this.timer);
    this.setState({
      startDate: date
    });

Open your browser. There it is. Now, let's select a date and hit generate, then let's hit change date, and select another date. Sweet, it replaces the date rather than having it have two separate dates and flipping back and forth.

large

That's how you solve that bug. Since it was such a tiny bug, let's just continue on in this video, and see what we can do. So we select a date, it works, although, when you hit change date and your birthday is a month before it creates a negative timer. That's not good.

You'll also see that we have a problem with it saying how old you're going to turn. If your birthday is in 2018 you're obviously not going to be turning 21 in -86 days. That doesn't even make any sense anyway, so if you say your birthday is August in you're still not going to turn 21 in 69 days if your birthday was in 2018. You're actually 0, you're not even born yet.

We got to make it so we can put in a date like September 15, 1997, hit generate, and have it display when I'm going to turn 21, and have that work. That's a lot more complex problem.

Let's go ahead and commit our code, and hop into that in the next video. Let's go into our terminal and say git status, git add ., and let's say git commit -m "fixed duplicate interval timers by clearing interval on change date". See you in the next video.

Resources