Last active
August 29, 2015 13:57
-
-
Save jesslilly/9859167 to your computer and use it in GitHub Desktop.
Implement a Timer in javascript. With tests. Took 1 hour to implement from scratch. Could be optimized.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
var expect = function(value1) { | |
return { | |
toBe: function(value2) { | |
document.getElementById('test').innerHTML += | |
"<pre>" | |
+ ((JSON.stringify(value1) === JSON.stringify(value2)) ? "Pass " : "Fail ") | |
+ "(val1: " + JSON.stringify(value1) | |
+ " val2: " + JSON.stringify(value2) | |
+ ")</pre><br\>"; | |
} | |
}; | |
}; | |
//expect(1).toBe(1); | |
//expect([0,1]).toBe([0,1]); | |
var Timer = (function(){ | |
var Timer = function(id) { | |
this._startDate = new Date(); | |
this._id = id; | |
this._elem = document.getElementById(id); | |
}; | |
Timer.prototype.getTime = function() { | |
var d = new Date (new Date() - this._startDate); | |
return d.toISOString().match(/\d\d:\d\d:\d\d/)[0]; | |
}; | |
Timer.prototype.start = function() { | |
var self = this; | |
window.setInterval(function() { | |
self._elem.innerHTML = self.getTime(); | |
},1000); | |
}; | |
return Timer; | |
})(); | |
var c = new Timer("timer"); | |
expect(c.getTime()).toBe("00:00:00"); | |
window.setTimeout(function() { | |
expect(c.getTime()).toBe("00:00:01"); | |
},1000); | |
c.start(); |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<h2>Timer</h2> | |
<div id="timer"></div> | |
<div id="test"></div> | |
<hr/> |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
I did this on codepen. Saving it here.