var Timer = (function(){ now = Date.now || function () {return (new Date()).getTime();} var txt = function(len){return new Array(len).join().replace(/(.|$)/g, function(){return ((Math.random()*36)|0).toString(36);})} var STOP = 0; var START = 1; var PAUSE = 2; function Timer(name, key){ this.name = name || txt(10); this.key = key || txt(10); _start = 0; _stop = 0; _total = 0; _status = 0; // STOP, START, PAUSE _laps = {}; } Timer.prototype.start = function(){ if (_status != START) { _start = now(); if(_status == STOP) { _total = 0; _laps = {}; } _status = START; } return this; }; Timer.prototype.stop = function(){ if (_status != STOP) { _stop = now(); _status = STOP; _total += _stop - _start; } return this; }; Timer.prototype.pause = function(){ if (_status == START) { _stop = now(); _status = PAUSE; _total += _stop - _start; } return this; }; Timer.prototype.resume = function(){ if (_status == PAUSE) { _status = START; _start = now(); } return this; } Timer.prototype.lap = function(name, key){ if (_status == START){ var tNow = now(); key = key || txt(10); name = name || txt(10); _laps[key] = { name : name, key : key, saved : tNow, total : _total + tNow - _start }; } return this; }; Timer.prototype.laps = function(key){ if (key){ return _laps[key]; } return _laps; } Timer.prototype.total = function(){ if (_status == START) { return (_total + now() - _start); } return _total; }; return Timer; })();