JavaScript

Object Oriented Programming with JavaScript : Timer Class3 min read

JavaScript with Oops is not much used by developers while creating application however we can make our life easy if we use JavaScript with Oops.

Let’s started object oriented programming in JavaScript by taking example of a Timer class, similar to the Timer control in windows application.

Create Class

Create the class Timer. Below code shows how to declare the class




Add Public Properties

To add public properties to the class we use this keyword as shown below

You can see that we have created 2 properties (Interval and Enable) of Timer class and assigned default values to them.

Add Events (If any)

Now we might want to add events to the class in case we need. For Timer class we need “Tick” event which will be fired every after “Interval”. Event are added the same way as the public properties.

Add Private Member Variables

We need 2 private variable in the class to hold the timer Id and the class instance. The private variable are added using ‘var’ keyword.

Add Functions

Public functions are also added the same way as public properties using this keyword. We need 2 function in the timer, first “Start” to start the timer and second “Stop” to stop the timer.

You can see I have incorporated the timer functionality using the setInterval function of the JavaScript. Our class is ready for use now.

Using the Class

To use the class first create the instance of Timer.

Now assign the value to its properties as needed.

Attach handler to the events

Now call the “Start” function to start the timer

To stop the timer anytime in between just call the “Stop” function.

 

 

3 Comments

Leave a Comment