Created
March 1, 2012 06:48
-
-
Save hongymagic/1947881 to your computer and use it in GitHub Desktop.
A simple timer implementation
This file contains 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
// Simple stop watch implementation in JavaScript. Supports functions | |
// such as: | |
// | |
// > `start`, `reset`, `time`, `pause`, `unpause` | |
// | |
// See [this demo](https://tinker.io/6154e/3) for information | |
// | |
window.Timer = (function () { | |
var Timer; | |
// | |
// A simple timer object | |
Timer = function () { | |
this.start(); | |
return this; | |
}; | |
// Start the timer (again if it was paused before) | |
Timer.prototype.start = function () { | |
this.s = (+new Date); | |
if (this.t) { | |
this.s -= this.t; | |
delete this.t; | |
} | |
return this.time(); | |
}; | |
// Returns current time reading since starting | |
Timer.prototype.time = function () { | |
if (this.t) { | |
return this.t; | |
} | |
return (+new Date) - this.s; | |
}; | |
// Restart the timer | |
Timer.prototype.restart = function () { | |
delete this.t; | |
return this.start(); | |
}; | |
// Pause the timer | |
Timer.prototype.pause = function () { | |
this.t = this.time(); | |
return this.t; | |
}; | |
// Unpause the timer | |
Timer.prototype.unpause = Timer.prototype.start; | |
// Is it paused? | |
Timer.prototype.paused = function () { | |
return this.t && this.t > 0; | |
}; | |
return Timer; | |
}()); |
This file contains 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
// Test | |
var timer = new Timer; | |
timer.start(); | |
console.log(timer.time()); | |
setTimeout(function () { console.log(timer.pause()); }, 1000); | |
setTimeout(function () { console.log(timer.time()); }, 1500); | |
setTimeout(function () { console.log(timer.unpause()); }, 2000); | |
setTimeout(function () { console.log(timer.time()); }, 2500); | |
setTimeout(function () { console.log(timer.time()); }, 2550); | |
setTimeout(function () { console.log(timer.restart()); }, 3000); | |
setTimeout(function () { console.log(timer.time()); }, 3500); | |
setTimeout(function () { console.log(timer.start()); }, 3500); | |
setTimeout(function () { console.log(timer.time()); }, 3550); | |
// 0 | |
// 1000 | |
// 1000 | |
// 1000 | |
// 1500 | |
// 1550 | |
// 0 | |
// 0 | |
// 0 | |
// 50 |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment