Last active
October 25, 2017 14:54
-
-
Save ahallora/afed3e859f6e54351e533bc4dcd07ad3 to your computer and use it in GitHub Desktop.
Tracker Object to track time - including pause and resume functionality
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
/* | |
LICENSE: MIT | |
Created by: Anders Holm-Jensen | |
Website: allora.dk | |
Date: 25-oct-2017 | |
*/ | |
const timestamp = () => ( Math.round( new Date() * 1 / 1000) ); | |
let tracker = { | |
data: { | |
state: 0, // 0 = stopped, 1 = active, 2 = paused | |
duration: 0, | |
pausedbuffer: 0, | |
started: 0, | |
ended: 0, | |
timer: null | |
}, | |
begin: function() { | |
if(this.data.state !== 0) return false; | |
this.data.state = 1; | |
this.data.duration = 0; | |
this.data.pausedbuffer = 0; | |
this.data.ended = 0; | |
this.data.started = timestamp(); | |
this.data.timer = setInterval(function() { | |
if(tracker.data.state === 1) { | |
console.log(Math.round(new Date() * 1 / 1000), 'tracking'); | |
} | |
}, 1000); | |
}, | |
stop: function() { | |
if(this.data.state === 0) return false; | |
this.data.state = 0; | |
this.data.ended = timestamp(); | |
this.data.timer = clearInterval(this.data.timer); | |
this.show(); | |
}, | |
pause: function() { | |
if(this.data.state !== 1) return false; | |
this.data.state = 2; | |
this.data.ended = timestamp(); // use ended as placeholder for paused time | |
}, | |
resume: function() { | |
if(this.data.state !== 2) return false; | |
this.data.state = 1; | |
this.data.pausedbuffer = this.data.pausedbuffer + (timestamp() - this.data.ended); | |
this.data.ended = 0; // clear paused time placeholder | |
}, | |
// helper functions | |
show: function() { | |
let duration = this.data.ended - this.data.started - this.data.pausedbuffer; | |
this.data.duration = (duration > 0) ? duration : 0; | |
console.table(this.data); | |
return this.data; | |
}, | |
toggle: function() { | |
if(this.data.state === 0) return this.begin(); | |
if(this.data.state === 1) return this.pause(); | |
if(this.data.state === 2) return this.resume(); | |
}, | |
isactive: function() { | |
return this.data.active; | |
} | |
} | |
/* | |
Start it by calling tracker.toggle() | |
Toggle between tracking/pause using tracker.toggle() | |
End trcaking by calling tracker.stop() | |
See tracking result by calling tracker.show() | |
*/ |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment