Skip to content

Instantly share code, notes, and snippets.

@jesslilly
Last active August 29, 2015 13:57
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save jesslilly/9859167 to your computer and use it in GitHub Desktop.
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.
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();
<h2>Timer</h2>
<div id="timer"></div>
<div id="test"></div>
<hr/>
@jesslilly
Copy link
Author

I did this on codepen. Saving it here.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment