02Geek HTML5 and JavaScript, TypeScript, React, Flash, ActionScript online School
Previous VideoNext Video

Interval Edge Cases

the main issues with setInterval are that you the develop needs to control edge cases. In this video we examine one of these type of issues. We look how to avoid memory leaks using intervals.

Video Transcript

00:00Now let's see just one more problem
00:01that we have with our application.
00:03If I send to my start timer 0, our application
00:07will fail us, right?
00:09Let's see why, because we sent 3 in our start timer,
00:13so it started our timer.
00:15But then if I said 0, it's going to start our timer again,
00:18even though it's at 0.
00:20And then 0 minus 1 will be minus 1,
00:22and then it's going to go on forever.
00:24So if I run my application one more time,
00:26it's going to continue on forever,
00:28because there's nothing here to block that user behavior.
00:32So to fix this problem, what I want to do
00:34is I want to take this if statement,
00:36and basically, instead of asking if there are seconds,
00:40to call the starter no matter what in our constructor.
00:43And instead of that, deal with that issue
00:46only when we're reaching our start timer.
00:48So in our start timer, I'm going
00:49to ask only if we got valid values, then will we continue?
00:55Now if we wanted to, we could say,
00:56well, if someone sends 0, that means
00:58they want the timer to be over.
01:00And I accept that.
01:01So how about if we take those two lines,
01:06and we make sure that they happen no matter what?
01:08So first of all, we're resetting the amount of time
01:11that's left, where we're getting rid of the interval
01:14if there was 1, and then we're just
01:15asking if there is any seconds,
01:17and we're going to start our interval.
01:19Now to top this, if we wanted to,
01:21we didn't have to use those brackets,
01:22because it's only one line, and we
01:24keep our code into only one line.
01:27So I'm saying you should always use the curler brackets,
01:29but it really just depends on how comfortable you are.
01:32And if you feel that you won't get confused by having code
01:35after your if statement, then it's really just down to that.
01:40A lot of times developers say, oh, never do that.
01:42But at the end of the day, they
01:44do that when they're working on their own projects,
01:46but they just say, don't do it,
01:47because that's what you're supposed to say.
01:50So because we're doing a formal tutorial,
01:51we're going to put it in those brackets
01:53and making sure that we're safe.
01:55And what I would say is, as long as you don't feel
01:57comfortable, do it.
01:58When you start feeling comfortable,
01:59just do whatever feels right.

Ready to Level Up Your Skills?

Join thousands of learners on 02GEEK and start your journey to becoming a coding expert today!

Enroll Now for Free!