Object Oriented Programming with JavaScript : Timer Class

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

// Declaring class "Timer"
var Timer = function()
{
    // ....        
    // Class body
    // ....
}

Add Public Properties

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

// Declaring class "Timer"
var Timer = function()
{        
    // Property: Frequency of elapse event of the timer in millisecond
    this.Interval = 1000;
    
    // Property: Whether the timer is enable or not
    this.Enable = new Boolean(false);
}

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.

// Declaring class "Timer"
var Timer = function()
{        
    // Property: Frequency of elapse event of the timer in millisecond
    this.Interval = 1000;
    
    // Property: Whether the timer is enable or not
    this.Enable = new Boolean(false);
    
    // Event: Timer tick
    this.Tick;
}

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.

// Declaring class "Timer"
var Timer = function()
{        
    // Property: Frequency of elapse event of the timer in millisecond
    this.Interval = 1000;
    
    // Property: Whether the timer is enable or not
    this.Enable = new Boolean(false);
    
    // Event: Timer tick
    this.Tick;
    
    // Member variable: Hold interval id of the timer
    var timerId = 0;
    
    // Member variable: Hold instance of this class
    var thisObject;
}

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.

// Declaring class "Timer"
var Timer = function()
{        
    // Property: Frequency of elapse event of the timer in millisecond
    this.Interval = 1000;
    
    // Property: Whether the timer is enable or not
    this.Enable = new Boolean(false);
    
    // Event: Timer tick
    this.Tick;
    
    // Member variable: Hold interval id of the timer
    var timerId = 0;
    
    // Member variable: Hold instance of this class
    var thisObject;
    
    // Function: Start the timer
    this.Start = function()
    {
        this.Enable = new Boolean(true);

        thisObject = this;
        if (thisObject.Enable)
        {
            thisObject.timerId = setInterval(
            function()
            {
                thisObject.Tick(); 
            }, thisObject.Interval);
        }
    };
    
    // Function: Stops the timer
    this.Stop = function()
    {            
        thisObject.Enable = new Boolean(false);
        clearInterval(thisObject.timerId);
    };

};

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.

var obj = new Timer();

Now assign the value to its properties as needed.

obj.Interval = 300;

Attach handler to the events

obj.Tick = timer_tick;

function timer_tick()
{
    // Do something..
}

Now call the "Start" function to start the timer

obj.Start();

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

obj.Stop();

Here is a working example of this class for you reference.

13 comment(S)


Carlos on Apr 2, 2009 11:08 AM

Very good article to get started in javascript programming and making a real usable class.

Greg on May 10, 2009 02:14 PM

Great article! I was looking for a reasonable JS OOP description and... found it! :) Keep writing such tutorials!

test on May 30, 2011 04:33 AM


test on May 30, 2011 04:34 AM

this is test msg

mahesh on May 30, 2011 04:34 AM

good one

Marcus on Sep 22, 2011 02:48 PM

Thanks for the tutorial. It's great. However, I can't pass any parameters into the function that I call when the timer ticks. Please can you show me how to modify it to add this functionality.

Thanks again.

Marcus

dotmeatpack on Sep 26, 2011 03:54 AM

It works but firebug detects errors, it says that thisObject.Tick() is not a function. I tried putting this:
var Timer = function() {
...
this.Tick = function(){
var x = 0;
}
...
}
To no avail the error still keeps on coming with every tick of the timer. Is there a remedy for this? I saw it happened on your sample page too, 22 errors come up saying the same thing.

Ben on Dec 30, 2011 08:35 AM

Greetings!

This is a great & simple template. I really like the elegance of just being able to create instances of timers & pass them around within my code. I found that if I set obj.Tick = myFunction(param1, param2, param3), it actually runs the function once then leaves the timer confused. The format of the timer in this case doesn't allow you to pass a function with parameters.

I'm working on solving this, but if anyone else has some insight, feel free to post. My initial thought is to add a property this.tickParams and have it parse the arguments object passed into the constructor, but this still muddies the water a bit more than I would like.

John Schmidt on Mar 20, 2012 02:48 AM

Hi,

I didn't experience any erros running the demo on current versions of IE, FF, Opera and Safari.

Great! Thanks for the code!

John

sponsored

Easwaran on Oct 4, 2012 06:49 AM

Excellent one!!!

Bakkie on Oct 31, 2013 04:36 AM

Great article, thanks heaps!

danielford on Mar 27, 2014 12:10 AM

JavaScript (JS) is a dynamic computer programming language. It is a prototype-based scripting language with dynamic typing and has first-class functions.
http://www.rasteredge.com/java-imaging/

mibson on Jul 4, 2014 02:21 AM

I'm trying to get my head around object oriented javascript and this tutorial solved a problem I've been trying to solve for 2 days. I really want to understad this: Why do you have to define "thisObject = this" and then use thisObject instead of "this"? I had similar code and was trying something in like this inside my class:

this.interval = 50;

this.fun = function()
{
code....
}

this.Start = function()
{
this.timerId = setInterval(fun(), this.interval);
}

It drives me crazy to not understand why...Thanks!

Leave a comment