Welcome to the Treehouse Community
Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.
Looking to learn something new?
Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.
Start your free trial

Christoph Rumpel
6,715 PointsNeed of object oriented JS?
Hi, i have build a litte JS script for start / stop timing and it works. Now i need multiple little "tracker" (start, pause, reset) on my site. That is why i am thinking about using OOP. Seems like my tracker could be built as a class with the functions start, pause and reset due the fact that i will have several ones on my site. Right? Or is there a better way? I guess there will be 1 to 10 tracker on my site, depending on the users needs. I am not that into JS yet, that is why i would love to hear some best practices or examples for a case like that. Thanks a lot and greets Christoph
18 Answers

Nick Pettit
Treehouse TeacherHey Christoph,
Jim and Andrew can answer this better than I can. I've emailed them about this post. :)

Randy Hoyt
Treehouse Guest TeacherHey Christoph,
I think you have the right idea with objects. Objects bind data (properties) and actions (methods) together into a single unit. A timer is a good example of that.
- The methods could be start, stop, and reset, like you say.
- The properties might be elapsed time (number of milliseconds) and whether or not the timer is currently running (boolean). (Alternatively, you might have a start time you would use to calculate the elapsed time.)
You don't technically need objects to pull this off. You could use variables (or DOM elements) to house the data and then pass that data into various functions. But in cases like this, where your data and the actions to be performed against it are so tightly integrated, then an object would be the right choice. You'll be able to use the timers more widely if all the data and actions are bundled up together in an object.
If you are looking to get started with objects in JavaScript, I'd recommend this article: Introduction to Object-Oriented JavaScript.

Christoph Rumpel
6,715 PointsHey,
thx Nick and Randy! I will go through the article and try my luck. Additionally i am thinking about making it a free plugin if everything works out ;-) Thanks for sharing your thoughts! Greets

Christoph Rumpel
6,715 PointsHey me again,
i have built a little prototype in a object oriented way. When you add the first timer everything works great, but if you load additional timers with the button it doesn't work that good anymore. One thing is that wenn i have one timer that is running and i load a second one, the first one stops running.
I just don't know if there are problems with several intervals on one site or if the way i code is not appropriate. It would be great if someone could help me in finding the problem and giving me feedback on my first object oriented JS example. Is this how it should be coded or am i using bad practices?
Example: http://christoph-rumpel.com/christoph/tests/simpletimetrack/
Thanks a lot!

Randy Hoyt
Treehouse Guest TeacherHey Christoph,
Overall, this is looking pretty good. I think you are having problems with multiple setIntervals conflicting. If you call the methods in the console, they all seem to be working correctly.
> createTimer()
> createTimer()
> timer[1].start()
> timer[2].start()
... wait a bit ...
> timer[1]
>> Timer
ID: "timer1"
el: <div>
elapsedTime: 66000
interval: 13361
isRunning: true
startTime: Mon Jan 07 2013 09:50:36 GMT-0500 (EST)
__proto__: Timer
> timer[2]
>> Timer
ID: "timer2"
el: <div>
elapsedTime: 301000
interval: 13368
isRunning: true
startTime: Mon Jan 07 2013 09:50:40 GMT-0500 (EST)
__proto__: Timer
I would recommend moving all of this to one setInterval. I would probably do this by creating another type of object, a Timer Control Panel kind of object or something. You already have the main components that you need for this: the array of timers as an array and the createTimer() function. Just make the array of timers a property and a createTimer() function a method.
The flow of the program would then work like this:
- Create a TimerControlPanel object (let's call it tcp)
- Clicking the button would call tcp.createTimer("timer1")
- Set an interval on a new method like tcp.update() that loops through all elements in the tcp.timers and calls their individual update() methods
Does that help?

Christoph Rumpel
6,715 PointsFirst of all thanks a lot for taking a look! Ok let me try to get that=)
I would have on intervall looping through all available timer objects and updating time or keep paused time if necessary. Right? Sounds actually quite good=)
Why would you recommend building another class for tcp? Since i only need one tcp, wouldn't it be better to use a normal function? Because you said "creating a new type of object". Or did you mean that? I am always thinking of OOP when i hear object ;-)
Thanks a lot! Cheers

Randy Hoyt
Treehouse Guest TeacherYep: it sounds like you understand what I had in mind. :~)
I would create an object because the data (the array of timers) is logically connected to the functions performed against that data (createTimers, update). Even if you are only creating one of them, it still makes sense as an object. You don't have to do it as an object, but it is a good practice to keep things together: it makes it encapsulated and modular and easier to maintain and all the other benefits of object-oriented programming.

Christoph Rumpel
6,715 PointsHey, i tried your approach, but it seems there is again a problem when i have several timers on the site. Did i wrote something wrong or is there again a problem with the setInterval? Cheers
New Version: http://christoph-rumpel.com/christoph/tests/simpletimetrack/index_v2.html

Randy Hoyt
Treehouse Guest Teacher(I assume you are familiar with the console since you are logging things there, but just in case you are not. In Chrome, you activate it by selecting View > Developer > JavaScript Console. It can be really helpful for troubleshooting issues like this.)
Open the console, and try the following:
- Click Create Timer.
- Click Create Timer again.
- Click Start on the first timer (timer[0]).
- Watch the console.
You'll notice that the interval is running and that it is in fact changing the time on the timer according to the interval correctly.
- Click Start on the second timer (timer[1]).
You'll notice that it is in fact changing the time on both timers correctly!
The issue must be the code in the update() method that changes the HTML of the item. I'll take a look at this later today, but that's where to start looking.
More soon ...

Christoph Rumpel
6,715 PointsHey, yeah that is what i ve been doing, but i cannot find the mistake. If you do not find time i understand. I will keep looking for the bug ;-) Thanks!

Randy Hoyt
Treehouse Guest TeacherAh, I see the issue. When the DOM changes, the previous version of the DOM elements stop existing and a whole new DOM is created. When you click Create Timer, all the elements referenced by earlier Timer.el properties stop existing ... so any call to a Timer.el property won't work.
I made an easy change to the code to get it working. Above this line --
this.el.innerHTML = this.elapsedTime;
-- add this one --
this.el = document.querySelector("#" + this.ID + " .timer-count")
this.el.innerHTML = this.elapsedTime;
This will select the element again during each update() command and put it in the Timer.el property.
It could be cleaner: I'd probably eliminate the Timer.el property altogether and just make it a local variable inside the update() method, like this:
el = document.querySelector("#" + this.ID + " .timer-count")
el.innerHTML = this.elapsedTime;
Does that help?

Christoph Rumpel
6,715 PointsHey, thanks again for the feedback. Guess you were right with the DOM problem, i did not know that! Unfortunately this didn't fix all. It seems like the update methode for every timer is called multiple time when there are more than one timer. Since yesterday i am trying to understand that, but until now without success. Another timer shouldn't get in conflict with a method of another object? Strange.
Regarding the el attribut. But i need it in the reset method too to clear the count. That is why i need to find the element in this method. When i delete the element property i am not sure how to get the right element? Cheers

Randy Hoyt
Treehouse Guest TeacherFirst, regarding the el attribute. You have the id of the element in this.id. In the last comment I had you add code to the update() method that finds the element again based on the ID. You'll need to add similar code in the reset() method to find the element again using this.ID.
I'll take a look at the multiple calls to the update() method a little later today.
More soon ...

Christoph Rumpel
6,715 PointsOf course! Totally logical with the element. I think i have spent too much time in this code ;-) Probably this is why i cannot find the problem with the multiple calls. Thanks Randy!

Randy Hoyt
Treehouse Guest TeacherAh, I see the issue with the multiple calls. You are setting the interval in the createTimer() method. Every time you create a new timer, you set another interval.
Hmmm ... I'm not sure where I would put that. There's no need to set the interval until a timer is created, so the create timer seems to make sense. I'd probably check the size of the timer array to figure out if this is the first timer you're creating. If it's the first one, add the interval; otherwise, don't.

Christoph Rumpel
6,715 PointsYes!! You are absolutely right!=) I did the trick with an if statement checking the array count. Randy really thanks a lot!! I really appreciate that!
I will let you know when i finished the project ;-) Cheers

Christoph Rumpel
6,715 PointsIn case anyone want to see the code, the url is now http://christoph-rumpel.com/christoph/tests/simpletimetrack/ again.

Randy Hoyt
Treehouse Guest TeacherLooking good ... nice work!