Skip to content

Instantly share code, notes, and snippets.

@probil
Created July 4, 2015 14:04
Show Gist options
  • Save probil/d6cca6f5fcbc13629e03 to your computer and use it in GitHub Desktop.
Save probil/d6cca6f5fcbc13629e03 to your computer and use it in GitHub Desktop.
Simple timer on JS
"use strict";
var Timer = function () {
var _time = 0;
var _interval = {};
return {
/**
* Starts timer
*/
start: function () {
_interval = setInterval(function () {
_time += 1;
}, 1000);
},
/**
* Set timer value (seconds)
* @param {Number} value
* @returns {boolean} False if data is not number
*/
setValue: function (value) {
if (value === Number(value)) {
_time = value;
return true
}
return false;
},
/**
* Returns current timer value in seconds
* @returns {number}
*/
getValue: function () {
return _time;
},
/**
* Returns current timer value in hh:mm:ss
* @returns {string}
*/
getFormattedValue: function () {
var sec_num = parseInt(_time, 10); // don't forget the second param
var hours = Math.floor(sec_num / 3600);
var minutes = Math.floor((sec_num - (hours * 3600)) / 60);
var seconds = sec_num - (hours * 3600) - (minutes * 60);
if (hours < 10) {
hours = "0" + hours;
}
if (minutes < 10) {
minutes = "0" + minutes;
}
if (seconds < 10) {
seconds = "0" + seconds;
}
return hours + ':' + minutes + ':' + seconds;
},
/**
* Stops timer
*/
stop: function () {
clearInterval(_interval);
_time = 0;
}
}
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment