Creating a stopwatch in Javascript and learning something

muhdmirzamz

MZ

Posted on January 24, 2020

Creating a stopwatch in Javascript and learning something

Hello, this is my first blog post on this site. I'm planning to have some content on here apart from Medium. So, here goes.

I've been thinking of getting back into web development. Specifically, web app development consisting of Node.JS and the rest of the javascript world. So, I've decided to make small websites here and there just to refresh my memory. In this post, I will talk about a bug I encountered when I was building a stopwatch.

This is the code for the main functionality controlling the stopwatch.

Alt Text

I thought it was okay until this happened.

Alt Text

As you can see, the seconds is okay. But the minutes and hours are not. My code appended "0"s each time it passes through this part here.

Alt Text

When I looked at the code, I expected minutes to remain at 0 since "0" + minutes is equals to 0. And I also expected minutes to go "00", "00" and so on and so forth.

So, when I look at this behaviour, I realise only strings have this behaviour, not Numbers.

I added some console logs to the code and checked for type.

Alt Text

And this was what showed up.

Alt Text

Now it is starting to make sense. That was why it appended the "0" instead of adding.

In conclusion, I still do not know what to expect when I add 2 variables together. But now, I know a little more.

💖 💪 🙅 🚩
muhdmirzamz
MZ

Posted on January 24, 2020

Join Our Newsletter. No Spam, Only the good stuff.

Sign up to receive the latest update from our blog.

Related