5c73a4df4d3d5e8e1f2dc7d7d55a32f1

please review this tiny javascript helper class.

I'd like this to be reviewed for any bad patterns, chances for memory leakage, browser-specific issues and any suggestions for optimizing it further.

/**
 * timer.class.js - Version 1.0.0
 * Last update: 01 Jan 2010
 *
 * @author Livingston Samuel - http://livingstonsamuel.com/
 * @source http://github.com/livingston/timer.class
 *
 * @license MIT License

Copyright (c) 2010 Livingston Samuel

Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.

*/

var Timer = function () {
	if( !( this instanceof arguments.callee ) ) {
		return new Timer();
	}

	var CLASS = arguments.callee, startTime, stopTime, timeList = [],
	fn = {
		"start": function () {
			startTime = (new Date()).getTime();
			stopTime = null;
			
			CLASS.prototype.stop = fn.stop;
			CLASS.prototype.elasped = fn.elasped;
			
			delete CLASS.prototype.start;
		},
		"elasped": function () {
			return (stopTime ? (stopTime - startTime) : ((new Date()).getTime() - startTime)) / 1000;
		},
		"stop": function () {
			stopTime = (new Date()).getTime();
			
			delete CLASS.prototype.stop;
			CLASS.prototype.start = fn.start;
			CLASS.prototype.list = fn.list;
			timeList.push(fn.elasped());
			
			return fn.elasped();
		},
		"list": timeList
	};

	CLASS.prototype.start = fn.start;
};

Refactorings

No refactoring yet !

Aacfa176a8d73ca75b90b6375151765a

paul.wilkins.myopenid.com

January 1, 2010, January 01, 2010 23:37, permalink

No rating. Login to rate!

An example usage within the comments would be useful.

What else do you think is not so good about this code, and in your mind requires further looking at?

D41d8cd98f00b204e9800998ecf8427e

lomax

January 14, 2010, January 14, 2010 19:15, permalink

No rating. Login to rate!

1. Don't modify a class definition inside of runtime code. (There are valid reasons to, but this is not one.)
2. Why are you force-checking the contextual this? Do you really care if this is reverse-interfaced onto a different type of object, or are you too lazy to always use the 'new' keyword when you instantiate?
3. Don't use commas to declare lists of local variables. Use semi-colons, and one line per variable. (performance, cross-engine bugs, readability)
4. Why are you hiding the real functionality of your class in a nested object?
5. If you are writing source for libraries or for consumption by anyone more than yourself, please double-check your spelling (elasped).
6. What in the sam hell pattern is deleting member methods about? If you need to know state, add a state property/property accessor method. Otherwise, track it in calling code. I would even suggest throwing exceptions if a method is called out of sequence (.start(); .start(); / .stop(); .stop();)
7. Is the internal structure of a Timer class really the place to track and log invocations of it? *shrug*
8. Why are you calculating the only value you apparently care about repeatedly instead of using the stored version?
9. Just because it's script doesn't exonerate you from following good programming structures and practices. In fact, it's much MORE important because you aren't given templates and compiler checks.
10. If you're taking the piss, well done. You hit some real high points here.

var Timer = function () {
    // private members
    var _startTime;
    var _state;
    var _invocations;

    // enum of possible states
    var _states={
        uninitialized:-1,
        stopped:0,
        started:1
    };

    // ctor
    new function Timer(){
        _state=_states.uninitialized;
        _invocations=[];
    }

    // public members
    this.Invocations=_invocations;
    
    // public methods
    this.Start=function(){
        if(_state==_states.started)throw new Error("Timer.start: The timer has already been started.");
        _state=_states.started;
        _startTime=new Date();
    }
    
    this.Elapsed=function(){
        switch(_state){
            case _states.uninitialized:
                throw new Error("Timer.elapsed: The timer has not been initialized.");
            case _states.started:
                return getDuration();
            case _states.stopped:
                return _invocations[_invocations.length-1]||0;
            default:
                return 0;
        }
    }

    this.Stop=function(){
        if(_state!=_states.started)throw new Error("Timer.start: The timer has not been started.");
        _invocations.push(getDuration());
        _state=_states.stopped;
        return this.Elapsed();
    }
    
    // private methods
    function getDuration(){
        if(!_startTime)return 0;
        return (new Date()-_startTime)/1000;
    }

};
<html>
<head>
    <title>Timer Test</title>
    <script src="Timer.js" type="text/javascript"></script>
    <script type="text/javascript">
        var _timer=new Timer();
    </script>
</head>
<body>
<button onclick="_timer.Start();">Start</button>
<button onclick="alert(_timer.Stop());">Stop</button>
<button onclick="alert(_timer.Elapsed());">Elapsed</button>
<button onclick="alert(_timer.Invocations.join('\n'));">Invocations</button>
</body>
</html>
B73e7f3fb3ff75f42897362f749c6711

Pharmacy Technician

January 30, 2010, January 30, 2010 09:24, permalink

No rating. Login to rate!

Keep posting stuff like this i really like it

Your refactoring





Format Copy from initial code

or Cancel