From 1650c3baf51b85912767ddc0ccd20abdc809fbff Mon Sep 17 00:00:00 2001
From: Walmik Deshpande
Date: Wed, 22 Mar 2017 05:13:48 -0700
Subject: [PATCH 01/15] Update README.md
---
README.md | 11 +++++++++--
1 file changed, 9 insertions(+), 2 deletions(-)
diff --git a/README.md b/README.md
index 21c1b16..b1da1ae 100644
--- a/README.md
+++ b/README.md
@@ -13,15 +13,22 @@
## Getting started
+Load the plugin in a script tag (right after loading jQuery) directly from CDNjs to get the current version of the timer plugin,
+
+```html
+
+
+```
+
If you are using bower,
```bash
bower install timer.jquery
```
-Alternatively you can [download][min] the jQuery timer plugin. Then, in your web page:
+Alternatively you can [download][min] the jQuery timer plugin and host it relative to your HTML file. Then, in your web page:
```html
-
+
-
+https://cdnjs.cloudflare.com/ajax/libs/timer.jquery/0.6.5/timer.jquery.min.js
```
If you are using bower,
@@ -25,7 +24,7 @@ If you are using bower,
bower install timer.jquery
```
-Alternatively you can [download][min] the jQuery timer plugin and host it relative to your HTML file. Then, in your web page:
+Alternatively you can [download][min] the jQuery timer plugin and host it relative to your HTML file. Once you have your preferred way to get jquery and the timer plugin, in your web page:
```html
diff --git a/dist/timer.jquery.js b/dist/timer.jquery.js
index 6d87de8..3202055 100644
--- a/dist/timer.jquery.js
+++ b/dist/timer.jquery.js
@@ -124,14 +124,12 @@
* Timer class to be instantiated on every element.
* All relative values will be stored at instance level.
*/
-
var Timer = function () {
/**
* Construct a Timer instance on the provided element with the given config.
* @param {Object} element HTML node as passed by jQuery
* @param {Object|String} config User extended options or a string (start, pause, resume etc)
*/
-
function Timer(element, config) {
_classCallCheck(this, Timer);
@@ -262,10 +260,7 @@
PLUGIN_NAME: 'timer',
TIMER_RUNNING: 'running',
TIMER_PAUSED: 'paused',
- DAYINSECONDS: 86400,
- THIRTYSIXHUNDRED: 3600,
- SIXTY: 60,
- TEN: 10
+ DAYINSECONDS: 86400
};
exports.default = Constants;
@@ -294,29 +289,17 @@
* @return {Object} Object with days, hours, minutes, totalMinutes, seconds and totalSeconds
*/
var _secondsToTimeObj = function _secondsToTimeObj() {
- var totalSeconds = arguments.length <= 0 || arguments[0] === undefined ? 0 : arguments[0];
-
- var days = 0;
- var hours = 0;
- var totalMinutes = Math.floor(totalSeconds / _constants2.default.SIXTY);
- var minutes = totalMinutes;
- var seconds = void 0;
-
- if (totalSeconds >= _constants2.default.DAYINSECONDS) {
- days = Math.floor(totalSeconds / _constants2.default.DAYINSECONDS);
- }
-
- if (totalSeconds >= _constants2.default.THIRTYSIXHUNDRED) {
- hours = Math.floor(totalSeconds % _constants2.default.DAYINSECONDS / _constants2.default.THIRTYSIXHUNDRED);
- }
-
- if (totalSeconds >= _constants2.default.SIXTY) {
- minutes = Math.floor(totalSeconds % _constants2.default.THIRTYSIXHUNDRED / _constants2.default.SIXTY);
- }
+ var totalSeconds = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : 0;
- seconds = totalSeconds % _constants2.default.SIXTY;
-
- return { days: days, hours: hours, minutes: minutes, totalMinutes: totalMinutes, seconds: seconds, totalSeconds: totalSeconds };
+ var totalMinutes = Math.floor(totalSeconds / 60);
+ return {
+ days: totalSeconds >= _constants2.default.DAYINSECONDS ? Math.floor(totalSeconds / _constants2.default.DAYINSECONDS) : 0,
+ hours: totalSeconds >= 3600 ? Math.floor(totalSeconds % _constants2.default.DAYINSECONDS / 3600) : 0,
+ totalMinutes: totalMinutes,
+ minutes: totalSeconds >= 60 ? Math.floor(totalSeconds % 3600 / 60) : totalMinutes,
+ seconds: totalSeconds % 60,
+ totalSeconds: totalSeconds
+ };
};
/**
@@ -328,12 +311,13 @@
/* global $:true */
var _paddedValue = function _paddedValue(num) {
num = parseInt(num, 10);
- if (num < 10) {
- return '0' + num;
- }
- return num;
+ return (num < 10 && '0') + num;
};
+ /**
+ * Method to return the base settings that can be used in case of no or missing options
+ * @return {Object} Default config
+ */
var getDefaultConfig = function getDefaultConfig() {
return {
seconds: 0, // Default seconds value to start timer from
@@ -354,7 +338,7 @@
* @return {Number} Return seconds passed since Jan 1, 1970
*/
var unixSeconds = function unixSeconds() {
- return Math.round(Date.now() / 1000);
+ return Math.round((Date.now ? Date.now() : new Date().getTime()) / 1000);
};
/**
@@ -393,9 +377,11 @@
var secondsToFormattedTime = function secondsToFormattedTime(seconds, formattedTime) {
var timeObj = _secondsToTimeObj(seconds);
var formatDef = [{ identifier: '%d', value: timeObj.days }, { identifier: '%h', value: timeObj.hours }, { identifier: '%m', value: timeObj.minutes }, { identifier: '%s', value: timeObj.seconds }, { identifier: '%g', value: timeObj.totalMinutes }, { identifier: '%t', value: timeObj.totalSeconds }, { identifier: '%D', value: _paddedValue(timeObj.days) }, { identifier: '%H', value: _paddedValue(timeObj.hours) }, { identifier: '%M', value: _paddedValue(timeObj.minutes) }, { identifier: '%S', value: _paddedValue(timeObj.seconds) }, { identifier: '%G', value: _paddedValue(timeObj.totalMinutes) }, { identifier: '%T', value: _paddedValue(timeObj.totalSeconds) }];
- formatDef.forEach(function (fmt) {
- formattedTime = formattedTime.replace(fmt.identifier, fmt.value);
- });
+
+ // Use `for` loop to support ie8 after transpilation
+ for (var i = 0; i < formatDef.length; i++) {
+ formattedTime = formattedTime.replace(formatDef[i].identifier, formatDef[i].value);
+ }
return formattedTime;
};
@@ -406,42 +392,37 @@
* @return {Number} Returns 330
*/
var durationTimeToSeconds = function durationTimeToSeconds(timeFormat) {
- if (!timeFormat) {
- throw new Error('durationTimeToSeconds expects a string argument!');
- }
-
- // Early return in case a number is passed
if (!isNaN(Number(timeFormat))) {
+ // A number was passed
return timeFormat;
}
timeFormat = timeFormat.toLowerCase();
- var days = timeFormat.match(/\d{1,2}d/); // Match 10d in 10d5h30m10s
- var hrs = timeFormat.match(/\d{1,2}h/); // Match 5h in 5h30m10s
- var mins = timeFormat.match(/\d{1,2}m/); // Match 30m in 5h30m10s
- var secs = timeFormat.match(/\d{1,2}s/); // Match 10s in 5h30m10s
+ var days = timeFormat.match(/\d+d/); // Match 10d in 10d5h30m10s
+ var hrs = timeFormat.match(/\d+h/); // Match 5h in 5h30m10s
+ var mins = timeFormat.match(/\d+m/); // Match 30m in 5h30m10s
+ var secs = timeFormat.match(/\d+s/); // Match 10s in 5h30m10s
if (!days && !hrs && !mins && !secs) {
throw new Error('Invalid string passed in durationTimeToSeconds!');
}
- var seconds = 0;
+ var seconds = 0;
if (days) {
- seconds += Number(days[0].replace('d', '') * _constants2.default.DAYINSECONDS);
+ seconds += Number(days[0].replace('d', '')) * _constants2.default.DAYINSECONDS;
}
if (hrs) {
- seconds += Number(hrs[0].replace('h', '') * _constants2.default.THIRTYSIXHUNDRED);
+ seconds += Number(hrs[0].replace('h', '')) * 3600;
}
if (mins) {
- seconds += Number(mins[0].replace('m', '')) * _constants2.default.SIXTY;
+ seconds += Number(mins[0].replace('m', '')) * 60;
}
if (secs) {
seconds += Number(secs[0].replace('s', ''));
}
-
return seconds;
};
@@ -460,13 +441,13 @@
} else if (editedTime.indexOf('min') > 0) {
editedTime = editedTime.replace(/\smin/g, '');
arr = editedTime.split(':');
- time = Number(arr[0] * _constants2.default.SIXTY) + Number(arr[1]);
+ time = Number(arr[0] * 60) + Number(arr[1]);
} else if (editedTime.match(/\d{1,2}:\d{2}:\d{2}:\d{2}/)) {
arr = editedTime.split(':');
- time = Number(arr[0] * _constants2.default.DAYINSECONDS) + Number(arr[1] * _constants2.default.THIRTYSIXHUNDRED) + Number(arr[2] * _constants2.default.SIXTY) + Number(arr[3]);
+ time = Number(arr[0] * _constants2.default.DAYINSECONDS) + Number(arr[1] * 3600) + Number(arr[2] * 60) + Number(arr[3]);
} else if (editedTime.match(/\d{1,2}:\d{2}:\d{2}/)) {
arr = editedTime.split(':');
- time = Number(arr[0] * _constants2.default.THIRTYSIXHUNDRED) + Number(arr[1] * _constants2.default.SIXTY) + Number(arr[2]);
+ time = Number(arr[0] * 3600) + Number(arr[1] * 60) + Number(arr[2]);
}
return time;
diff --git a/dist/timer.jquery.min.js b/dist/timer.jquery.min.js
index 809841d..0de479a 100644
--- a/dist/timer.jquery.min.js
+++ b/dist/timer.jquery.min.js
@@ -1 +1 @@
-/*! timer.jquery 0.6.3 2016-08-09*/!function(a){function b(d){if(c[d])return c[d].exports;var e=c[d]={exports:{},id:d,loaded:!1};return a[d].call(e.exports,e,e.exports,b),e.loaded=!0,e.exports}var c={};return b.m=a,b.c=c,b.p="",b(0)}([function(a,b,c){"use strict";function d(a){return a&&a.__esModule?a:{"default":a}}var e=c(1),f=d(e),g=c(2),h=d(g);!function(){$.fn.timer=function(a){return a=a||"start",this.each(function(){$.data(this,h["default"].PLUGIN_NAME)instanceof f["default"]||$.data(this,h["default"].PLUGIN_NAME,new f["default"](this,a));var b=$.data(this,h["default"].PLUGIN_NAME);"string"==typeof a?"function"==typeof b[a]&&b[a]():b.start()})}}()},function(a,b,c){"use strict";function d(a){return a&&a.__esModule?a:{"default":a}}function e(a,b){if(!(a instanceof b))throw new TypeError("Cannot call a class as a function")}Object.defineProperty(b,"__esModule",{value:!0});var f=function(){function a(a,b){for(var c=0;c=f["default"].DAYINSECONDS&&(b=Math.floor(a/f["default"].DAYINSECONDS)),a>=f["default"].THIRTYSIXHUNDRED&&(c=Math.floor(a%f["default"].DAYINSECONDS/f["default"].THIRTYSIXHUNDRED)),a>=f["default"].SIXTY&&(e=Math.floor(a%f["default"].THIRTYSIXHUNDRED/f["default"].SIXTY)),g=a%f["default"].SIXTY,{days:b,hours:c,minutes:e,totalMinutes:d,seconds:g,totalSeconds:a}},h=function(a){return a=parseInt(a,10),a<10?"0"+a:a},i=function(){return{seconds:0,editable:!1,duration:null,callback:function(){console.log("Time up!")},repeat:!1,countdown:!1,format:null,updateFrequency:500}},j=function(){return Math.round(Date.now()/1e3)},k=function(a){var b=g(a);if(b.days)return b.days+":"+h(b.hours)+":"+h(b.minutes)+":"+h(b.seconds);if(b.hours)return b.hours+":"+h(b.minutes)+":"+h(b.seconds);var c="";return c=b.minutes?b.minutes+":"+h(b.seconds)+" min":b.seconds+" sec"},l=function(a,b){var c=g(a),d=[{identifier:"%d",value:c.days},{identifier:"%h",value:c.hours},{identifier:"%m",value:c.minutes},{identifier:"%s",value:c.seconds},{identifier:"%g",value:c.totalMinutes},{identifier:"%t",value:c.totalSeconds},{identifier:"%D",value:h(c.days)},{identifier:"%H",value:h(c.hours)},{identifier:"%M",value:h(c.minutes)},{identifier:"%S",value:h(c.seconds)},{identifier:"%G",value:h(c.totalMinutes)},{identifier:"%T",value:h(c.totalSeconds)}];return d.forEach(function(a){b=b.replace(a.identifier,a.value)}),b},m=function(a){if(!a)throw new Error("durationTimeToSeconds expects a string argument!");if(!isNaN(Number(a)))return a;a=a.toLowerCase();var b=a.match(/\d{1,2}d/),c=a.match(/\d{1,2}h/),d=a.match(/\d{1,2}m/),e=a.match(/\d{1,2}s/);if(!(b||c||d||e))throw new Error("Invalid string passed in durationTimeToSeconds!");var g=0;return b&&(g+=Number(b[0].replace("d","")*f["default"].DAYINSECONDS)),c&&(g+=Number(c[0].replace("h","")*f["default"].THIRTYSIXHUNDRED)),d&&(g+=Number(d[0].replace("m",""))*f["default"].SIXTY),e&&(g+=Number(e[0].replace("s",""))),g},n=function(a){var b=void 0,c=void 0;return a.indexOf("sec")>0?c=Number(a.replace(/\ssec/g,"")):a.indexOf("min")>0?(a=a.replace(/\smin/g,""),b=a.split(":"),c=Number(b[0]*f["default"].SIXTY)+Number(b[1])):a.match(/\d{1,2}:\d{2}:\d{2}:\d{2}/)?(b=a.split(":"),c=Number(b[0]*f["default"].DAYINSECONDS)+Number(b[1]*f["default"].THIRTYSIXHUNDRED)+Number(b[2]*f["default"].SIXTY)+Number(b[3])):a.match(/\d{1,2}:\d{2}:\d{2}/)&&(b=a.split(":"),c=Number(b[0]*f["default"].THIRTYSIXHUNDRED)+Number(b[1]*f["default"].SIXTY)+Number(b[2])),c},o=function(a,b){a.state=b,$(a.element).data("state",b)},p=function(a){$(a.element).on("focus",function(){a.pause()}),$(a.element).on("blur",function(){a.totalSeconds=n($(a.element)[a.html]()),a.resume()})},q=function(a){return a.totalSeconds=j()-a.startTime,a.config.countdown?(a.totalSeconds=a.config.duration-a.totalSeconds,0===a.totalSeconds&&(clearInterval(a.intervalId),o(a,f["default"].TIMER_STOPPED),a.config.callback(),$(a.element).data("seconds")),void a.render()):(a.render(),void(a.config.duration&&a.totalSeconds>0&&a.totalSeconds%a.config.duration===0&&(a.config.callback&&a.config.callback(),a.config.repeat||(clearInterval(a.intervalId),o(a,f["default"].TIMER_STOPPED),a.config.duration=null))))};b["default"]={getDefaultConfig:i,unixSeconds:j,secondsToPrettyTime:k,secondsToFormattedTime:l,durationTimeToSeconds:m,prettyTimeToSeconds:n,setState:o,makeEditable:p,intervalHandler:q}}]);
\ No newline at end of file
+/*! timer.jquery 0.6.4 2017-03-22*/!function(a){function b(d){if(c[d])return c[d].exports;var e=c[d]={exports:{},id:d,loaded:!1};return a[d].call(e.exports,e,e.exports,b),e.loaded=!0,e.exports}var c={};return b.m=a,b.c=c,b.p="",b(0)}([function(a,b,c){"use strict";function d(a){return a&&a.__esModule?a:{"default":a}}var e=c(1),f=d(e),g=c(2),h=d(g);!function(){$.fn.timer=function(a){return a=a||"start",this.each(function(){$.data(this,h["default"].PLUGIN_NAME)instanceof f["default"]||$.data(this,h["default"].PLUGIN_NAME,new f["default"](this,a));var b=$.data(this,h["default"].PLUGIN_NAME);"string"==typeof a?"function"==typeof b[a]&&b[a]():b.start()})}}()},function(a,b,c){"use strict";function d(a){return a&&a.__esModule?a:{"default":a}}function e(a,b){if(!(a instanceof b))throw new TypeError("Cannot call a class as a function")}Object.defineProperty(b,"__esModule",{value:!0});var f=function(){function a(a,b){for(var c=0;c0&&void 0!==arguments[0]?arguments[0]:0,b=Math.floor(a/60);return{days:a>=f["default"].DAYINSECONDS?Math.floor(a/f["default"].DAYINSECONDS):0,hours:a>=3600?Math.floor(a%f["default"].DAYINSECONDS/3600):0,totalMinutes:b,minutes:a>=60?Math.floor(a%3600/60):b,seconds:a%60,totalSeconds:a}},h=function(a){return a=parseInt(a,10),(a<10&&"0")+a},i=function(){return{seconds:0,editable:!1,duration:null,callback:function(){console.log("Time up!")},repeat:!1,countdown:!1,format:null,updateFrequency:500}},j=function(){return Math.round((Date.now?Date.now():(new Date).getTime())/1e3)},k=function(a){var b=g(a);if(b.days)return b.days+":"+h(b.hours)+":"+h(b.minutes)+":"+h(b.seconds);if(b.hours)return b.hours+":"+h(b.minutes)+":"+h(b.seconds);var c="";return c=b.minutes?b.minutes+":"+h(b.seconds)+" min":b.seconds+" sec"},l=function(a,b){for(var c=g(a),d=[{identifier:"%d",value:c.days},{identifier:"%h",value:c.hours},{identifier:"%m",value:c.minutes},{identifier:"%s",value:c.seconds},{identifier:"%g",value:c.totalMinutes},{identifier:"%t",value:c.totalSeconds},{identifier:"%D",value:h(c.days)},{identifier:"%H",value:h(c.hours)},{identifier:"%M",value:h(c.minutes)},{identifier:"%S",value:h(c.seconds)},{identifier:"%G",value:h(c.totalMinutes)},{identifier:"%T",value:h(c.totalSeconds)}],e=0;e0?c=Number(a.replace(/\ssec/g,"")):a.indexOf("min")>0?(a=a.replace(/\smin/g,""),b=a.split(":"),c=Number(60*b[0])+Number(b[1])):a.match(/\d{1,2}:\d{2}:\d{2}:\d{2}/)?(b=a.split(":"),c=Number(b[0]*f["default"].DAYINSECONDS)+Number(3600*b[1])+Number(60*b[2])+Number(b[3])):a.match(/\d{1,2}:\d{2}:\d{2}/)&&(b=a.split(":"),c=Number(3600*b[0])+Number(60*b[1])+Number(b[2])),c},o=function(a,b){a.state=b,$(a.element).data("state",b)},p=function(a){$(a.element).on("focus",function(){a.pause()}),$(a.element).on("blur",function(){a.totalSeconds=n($(a.element)[a.html]()),a.resume()})},q=function(a){return a.totalSeconds=j()-a.startTime,a.config.countdown?(a.totalSeconds=a.config.duration-a.totalSeconds,0===a.totalSeconds&&(clearInterval(a.intervalId),o(a,f["default"].TIMER_STOPPED),a.config.callback(),$(a.element).data("seconds")),void a.render()):(a.render(),void(a.config.duration&&a.totalSeconds>0&&a.totalSeconds%a.config.duration===0&&(a.config.callback&&a.config.callback(),a.config.repeat||(clearInterval(a.intervalId),o(a,f["default"].TIMER_STOPPED),a.config.duration=null))))};b["default"]={getDefaultConfig:i,unixSeconds:j,secondsToPrettyTime:k,secondsToFormattedTime:l,durationTimeToSeconds:m,prettyTimeToSeconds:n,setState:o,makeEditable:p,intervalHandler:q}}]);
\ No newline at end of file
diff --git a/package.json b/package.json
index cd11a2f..97c73f4 100644
--- a/package.json
+++ b/package.json
@@ -2,7 +2,7 @@
"name": "timer.jquery",
"description": "Start/Stop/Resume/Remove a timer inside any HTML element.",
"author": "Walmik Deshpande",
- "version": "0.6.4",
+ "version": "0.6.5",
"repository": {
"type": "git",
"url": "git://github.com/walmik/timer.jquery.git"
diff --git a/src/constants.js b/src/constants.js
index f22a0bd..13f3405 100644
--- a/src/constants.js
+++ b/src/constants.js
@@ -2,10 +2,7 @@ const Constants = {
PLUGIN_NAME: 'timer',
TIMER_RUNNING: 'running',
TIMER_PAUSED: 'paused',
- DAYINSECONDS: 86400,
- THIRTYSIXHUNDRED: 3600,
- SIXTY: 60,
- TEN: 10
+ DAYINSECONDS: 86400
};
export default Constants;
diff --git a/src/utils.js b/src/utils.js
index f2a426e..bbacbf0 100644
--- a/src/utils.js
+++ b/src/utils.js
@@ -8,27 +8,21 @@ import Constants from './constants';
* @return {Object} Object with days, hours, minutes, totalMinutes, seconds and totalSeconds
*/
const _secondsToTimeObj = (totalSeconds = 0) => {
- let days = 0;
- let hours = 0;
- let totalMinutes = Math.floor(totalSeconds / Constants.SIXTY);
- let minutes = totalMinutes;
- let seconds;
-
- if (totalSeconds >= Constants.DAYINSECONDS) {
- days = Math.floor(totalSeconds / Constants.DAYINSECONDS);
- }
-
- if (totalSeconds >= Constants.THIRTYSIXHUNDRED) {
- hours = Math.floor(totalSeconds % Constants.DAYINSECONDS / Constants.THIRTYSIXHUNDRED);
- }
-
- if (totalSeconds >= Constants.SIXTY) {
- minutes = Math.floor(totalSeconds % Constants.THIRTYSIXHUNDRED / Constants.SIXTY);
- }
-
- seconds = totalSeconds % Constants.SIXTY;
-
- return {days, hours, minutes, totalMinutes, seconds, totalSeconds};
+ let totalMinutes = Math.floor(totalSeconds / 60);
+ return {
+ days: totalSeconds >= Constants.DAYINSECONDS ?
+ Math.floor(totalSeconds / Constants.DAYINSECONDS) :
+ 0,
+ hours: totalSeconds >= 3600 ?
+ Math.floor(totalSeconds % Constants.DAYINSECONDS / 3600) :
+ 0,
+ totalMinutes,
+ minutes: totalSeconds >= 60 ?
+ Math.floor(totalSeconds % 3600 / 60) :
+ totalMinutes,
+ seconds: totalSeconds % 60,
+ totalSeconds
+ };
};
/**
@@ -39,12 +33,13 @@ const _secondsToTimeObj = (totalSeconds = 0) => {
*/
const _paddedValue = num => {
num = parseInt(num, 10);
- if (num < 10) {
- return '0' + num;
- }
- return num;
+ return (num < 10 && '0') + num;
};
+/**
+ * Method to return the base settings that can be used in case of no or missing options
+ * @return {Object} Default config
+ */
const getDefaultConfig = () => ({
seconds: 0, // Default seconds value to start timer from
editable: false, // Allow making changes to the time by clicking on it
@@ -61,7 +56,7 @@ const getDefaultConfig = () => ({
/**
* @return {Number} Return seconds passed since Jan 1, 1970
*/
-const unixSeconds = () => (Math.round(Date.now() / 1000));
+const unixSeconds = () => Math.round((Date.now ? Date.now() : new Date().getTime()) / 1000);
/**
* Convert seconds to pretty time.
@@ -113,9 +108,11 @@ const secondsToFormattedTime = (seconds, formattedTime) => {
{identifier: '%G', value: _paddedValue(timeObj.totalMinutes)},
{identifier: '%T', value: _paddedValue(timeObj.totalSeconds)}
];
- formatDef.forEach(function(fmt) {
- formattedTime = formattedTime.replace(fmt.identifier, fmt.value);
- });
+
+ // Use `for` loop to support ie8 after transpilation
+ for (let i = 0; i < formatDef.length; i++) {
+ formattedTime = formattedTime.replace(formatDef[i].identifier, formatDef[i].value);
+ }
return formattedTime;
};
@@ -126,42 +123,37 @@ const secondsToFormattedTime = (seconds, formattedTime) => {
* @return {Number} Returns 330
*/
const durationTimeToSeconds = timeFormat => {
- if (!timeFormat) {
- throw new Error('durationTimeToSeconds expects a string argument!');
- }
-
- // Early return in case a number is passed
if (!isNaN(Number(timeFormat))) {
+ // A number was passed
return timeFormat;
}
timeFormat = timeFormat.toLowerCase();
- let days = timeFormat.match(/\d{1,2}d/); // Match 10d in 10d5h30m10s
- let hrs = timeFormat.match(/\d{1,2}h/); // Match 5h in 5h30m10s
- let mins = timeFormat.match(/\d{1,2}m/); // Match 30m in 5h30m10s
- let secs = timeFormat.match(/\d{1,2}s/); // Match 10s in 5h30m10s
+ let days = timeFormat.match(/\d+d/); // Match 10d in 10d5h30m10s
+ let hrs = timeFormat.match(/\d+h/); // Match 5h in 5h30m10s
+ let mins = timeFormat.match(/\d+m/); // Match 30m in 5h30m10s
+ let secs = timeFormat.match(/\d+s/); // Match 10s in 5h30m10s
if (!days && !hrs && !mins && !secs) {
throw new Error('Invalid string passed in durationTimeToSeconds!');
}
- let seconds = 0;
+ let seconds = 0;
if (days) {
- seconds += Number(days[0].replace('d', '') * Constants.DAYINSECONDS);
+ seconds += Number(days[0].replace('d', '')) * Constants.DAYINSECONDS;
}
if (hrs) {
- seconds += Number(hrs[0].replace('h', '') * Constants.THIRTYSIXHUNDRED);
+ seconds += Number(hrs[0].replace('h', '')) * 3600;
}
if (mins) {
- seconds += Number(mins[0].replace('m', '')) * Constants.SIXTY;
+ seconds += Number(mins[0].replace('m', '')) * 60;
}
if (secs) {
seconds += Number(secs[0].replace('s', ''));
}
-
return seconds;
};
@@ -180,14 +172,14 @@ const prettyTimeToSeconds = editedTime => {
} else if (editedTime.indexOf('min') > 0) {
editedTime = editedTime.replace(/\smin/g, '');
arr = editedTime.split(':');
- time = Number(arr[0] * Constants.SIXTY) + Number(arr[1]);
+ time = Number(arr[0] * 60) + Number(arr[1]);
} else if (editedTime.match(/\d{1,2}:\d{2}:\d{2}:\d{2}/)) {
arr = editedTime.split(':');
- time = Number(arr[0] * Constants.DAYINSECONDS) + Number(arr[1] * Constants.THIRTYSIXHUNDRED) +
- Number(arr[2] * Constants.SIXTY) + Number(arr[3]);
+ time = Number(arr[0] * Constants.DAYINSECONDS) + Number(arr[1] * 3600) +
+ Number(arr[2] * 60) + Number(arr[3]);
} else if (editedTime.match(/\d{1,2}:\d{2}:\d{2}/)) {
arr = editedTime.split(':');
- time = Number(arr[0] * Constants.THIRTYSIXHUNDRED) + Number(arr[1] * Constants.SIXTY) + Number(arr[2]);
+ time = Number(arr[0] * 3600) + Number(arr[1] * 60) + Number(arr[2]);
}
return time;
From 17a4582bbcf642267d1b1a99323c5168bf219a3a Mon Sep 17 00:00:00 2001
From: Walmik Deshpande
Date: Sat, 15 Apr 2017 17:33:39 -0700
Subject: [PATCH 03/15] Move to ES 5
---
.babelrc | 3 -
.eslintrc.json | 8 -
.jscsrc | 9 +
CONTRIBUTING.md | 12 +-
Gruntfile.js | 47 +-
LICENSE-MIT | 2 +-
bower.json | 6 +-
dist/timer.jquery.js | 927 +++++++++++++++++----------------------
dist/timer.jquery.min.js | 2 +-
index.html | 365 ---------------
package.json | 30 +-
src/Timer.js | 175 ++++----
src/constants.js | 4 +-
src/index.js | 61 ++-
src/utils.js | 120 ++---
test/utils-test.js | 24 +-
webpack.config.js | 19 -
17 files changed, 661 insertions(+), 1153 deletions(-)
delete mode 100644 .babelrc
delete mode 100644 .eslintrc.json
create mode 100644 .jscsrc
delete mode 100644 index.html
delete mode 100644 webpack.config.js
diff --git a/.babelrc b/.babelrc
deleted file mode 100644
index 7b37dd5..0000000
--- a/.babelrc
+++ /dev/null
@@ -1,3 +0,0 @@
-{
- "presets": ["es2015"]
-}
diff --git a/.eslintrc.json b/.eslintrc.json
deleted file mode 100644
index 78ab966..0000000
--- a/.eslintrc.json
+++ /dev/null
@@ -1,8 +0,0 @@
-{
- "extends": "google",
- "installedESLint": true,
- "rules": {
- "indent": ["error", "tab"],
- "max-len": ["error", 120]
- }
-}
diff --git a/.jscsrc b/.jscsrc
new file mode 100644
index 0000000..15fbb0b
--- /dev/null
+++ b/.jscsrc
@@ -0,0 +1,9 @@
+{
+ "preset": "jquery",
+ "requireSpacesInsideParentheses": false,
+ "validateQuoteMarks": true,
+ "requireSpacesInsideBrackets": false,
+ "requireSpacesInsideObjectBrackets": false,
+ "maximumLineLength": 120,
+ "requirePaddingNewLinesBeforeLineComments": false
+}
\ No newline at end of file
diff --git a/CONTRIBUTING.md b/CONTRIBUTING.md
index 0d33d3a..36bee3d 100644
--- a/CONTRIBUTING.md
+++ b/CONTRIBUTING.md
@@ -2,15 +2,15 @@
This project is an outcome of a lot of contributions from developers who have been kind enough to point out any issues and/or have taken the time to create pull requests that fix issues or add new features to this repo. In other words, contributions are welcome :) Here are some guidelines to consider:
-- The jQuery timer plugin is written in ES6. It uses babel along with webpack for transpiling to ES5
+- The jQuery timer plugin is written in ES 5. It was written in ES 6 when I once felt that the browsers will catchup to ES6 and we ll not have to transpile anymore. The transpiled version of the jQuery timer adds 30% cruft to the code just to manage the fancy syntax. I moved away from it coz I realized users of this plugin don't care about that and should not be subjected to it.
- All source code is in the `src` directory. Any changes you make should ideally happen in the files inside `src` (unless you are making changes to the README or this file itself)
- To start contributing code changes, fork this repo to your Github account and clone it in your local computer
- Run `npm install` to install all the dependencies
-- The package.json has all the required commands for you to test and transpile
- * `npm test` to run eslint and the unit tests
- * `npm run webpack` to transpile the scripts from the _src_ directory to _dist/timer.jquery.js_
- * `npm grunt` for minifying the transpiled file to _dist/timer.jquery.min.js_
+- The package.json has all the required commands for you to test, lint, style check and put together a production file
+ * `npm test` to run unit tests
+ * `npm run build` for running jscs, jshint, concat and uglify to generate timer.jquery.js and timer.jquery.min.js inside dist/
+ * `npm run watch` Watch over files from src and test as you work on them to running jscs, jshint, concat and uglify on changes
- Once you ve made the changes and are sure that the existing tests pass, commit them to your _origin_ and issue a Pull Request to the upstream (this repo)
- Please write tests for your changes
-That's it. Happy coding!
\ No newline at end of file
+That's it. Time is precious, use it wisely & Happy Coding :)
\ No newline at end of file
diff --git a/Gruntfile.js b/Gruntfile.js
index a48d244..e1a15cb 100644
--- a/Gruntfile.js
+++ b/Gruntfile.js
@@ -1,21 +1,46 @@
-module.exports = function (grunt) {
+module.exports = function(grunt) {
+ var commonTasks = ['jscs', 'jshint', 'concat', 'uglify'];
grunt.initConfig({
pkg: grunt.file.readJSON('package.json'),
- uglify: {
+ jscs: {
+ src: ['Gruntfile.js', 'src/*.js', 'test/*.js']
+ },
+
+ jshint: {
+ all: ['Gruntfile.js', 'src/*.js', 'test/*.js']
+ },
+
+ concat: {
options: {
- banner: '/*! <%= pkg.name %> <%= pkg.version %> <%=grunt.template.today("yyyy-mm-dd")%>*/'
+ banner: [
+ '/*! <%= pkg.name %> <%= pkg.version %> <%=grunt.template.today("yyyy-mm-dd")%>*/\n',
+ '(function() {\n'
+ ].join(''),
+ footer: '} ());'
},
dist: {
- src: ['dist/timer.jquery.js'],
+ src: [
+ 'src/constants.js',
+ 'src/utils.js',
+ 'src/Timer.js',
+ 'src/index.js'
+ ],
+ dest: 'dist/timer.jquery.js'
+ }
+ },
+
+ uglify: {
+ dist: {
+ src: 'dist/timer.jquery.js',
dest: 'dist/timer.jquery.min.js'
- },
+ }
},
watch: {
scripts: {
- files: ['dist/timer.jquery.js'],
- tasks: ['uglify'],
+ files: ['src/*.js'],
+ tasks: commonTasks,
options: {
nospawn: true
}
@@ -23,9 +48,11 @@ module.exports = function (grunt) {
}
});
+ grunt.loadNpmTasks('grunt-jscs');
+ grunt.loadNpmTasks('grunt-contrib-jshint');
+ grunt.loadNpmTasks('grunt-contrib-concat');
grunt.loadNpmTasks('grunt-contrib-uglify');
grunt.loadNpmTasks('grunt-contrib-watch');
- //register default task
- grunt.registerTask('default', 'watch');
-}
+ grunt.registerTask('default', commonTasks);
+};
diff --git a/LICENSE-MIT b/LICENSE-MIT
index fd1c181..b9a8bc2 100644
--- a/LICENSE-MIT
+++ b/LICENSE-MIT
@@ -1,4 +1,4 @@
-Copyright (c) 2016 Walmik Deshpande
+Copyright (c) 2017 Walmik Deshpande
Permission is hereby granted, free of charge, to any person
obtaining a copy of this software and associated documentation
diff --git a/bower.json b/bower.json
index 5d3cf71..90302d9 100644
--- a/bower.json
+++ b/bower.json
@@ -1,15 +1,11 @@
{
"name": "timer.jquery",
"ignore": [
- ".babelrc",
- ".eslintrc.json",
".gitignore",
".travis.yml",
"Gruntfile.js",
- "index.html",
"package.json",
- "test",
- "webpack.config.js"
+ "test"
],
"dependencies": {
"jquery": ">=1.9.0"
diff --git a/dist/timer.jquery.js b/dist/timer.jquery.js
index 3202055..61c52d3 100644
--- a/dist/timer.jquery.js
+++ b/dist/timer.jquery.js
@@ -1,537 +1,424 @@
-/******/ (function(modules) { // webpackBootstrap
-/******/ // The module cache
-/******/ var installedModules = {};
-
-/******/ // The require function
-/******/ function __webpack_require__(moduleId) {
-
-/******/ // Check if module is in cache
-/******/ if(installedModules[moduleId])
-/******/ return installedModules[moduleId].exports;
-
-/******/ // Create a new module (and put it into the cache)
-/******/ var module = installedModules[moduleId] = {
-/******/ exports: {},
-/******/ id: moduleId,
-/******/ loaded: false
-/******/ };
-
-/******/ // Execute the module function
-/******/ modules[moduleId].call(module.exports, module, module.exports, __webpack_require__);
-
-/******/ // Flag the module as loaded
-/******/ module.loaded = true;
-
-/******/ // Return the exports of the module
-/******/ return module.exports;
-/******/ }
-
-
-/******/ // expose the modules object (__webpack_modules__)
-/******/ __webpack_require__.m = modules;
-
-/******/ // expose the module cache
-/******/ __webpack_require__.c = installedModules;
-
-/******/ // __webpack_public_path__
-/******/ __webpack_require__.p = "";
-
-/******/ // Load entry module and return exports
-/******/ return __webpack_require__(0);
-/******/ })
-/************************************************************************/
-/******/ ([
-/* 0 */
-/***/ function(module, exports, __webpack_require__) {
-
- 'use strict';
-
- var _Timer = __webpack_require__(1);
-
- var _Timer2 = _interopRequireDefault(_Timer);
-
- var _constants = __webpack_require__(2);
-
- var _constants2 = _interopRequireDefault(_constants);
-
- function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
-
- /* global $:true */
-
- (function () {
- $.fn.timer = function (options) {
- options = options || 'start';
-
- return this.each(function () {
- if (!($.data(this, _constants2.default.PLUGIN_NAME) instanceof _Timer2.default)) {
- /**
- * Create a new data attribute on the element to hold the plugin name
- * This way we can know which plugin(s) is/are initialized on the element later
- */
- $.data(this, _constants2.default.PLUGIN_NAME, new _Timer2.default(this, options));
- }
-
- /**
- * Use the instance of this plugin derived from the data attribute for this element
- * to conduct whatever action requested as a string parameter.
- */
- var instance = $.data(this, _constants2.default.PLUGIN_NAME);
-
- /**
- * Provision for calling a function from this plugin
- * without initializing it all over again
- */
- if (typeof options === 'string') {
- if (typeof instance[options] === 'function') {
- /*
- Pass in 'instance' to provide for the value of 'this' in the called function
- */
- instance[options]();
- }
- } else {
- instance.start();
- }
- });
- };
- })();
-
-/***/ },
-/* 1 */
-/***/ function(module, exports, __webpack_require__) {
-
- 'use strict';
-
- Object.defineProperty(exports, "__esModule", {
- value: true
- });
-
- var _createClass = function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; }(); /* global $:true */
-
-
- var _constants = __webpack_require__(2);
-
- var _constants2 = _interopRequireDefault(_constants);
-
- var _utils = __webpack_require__(3);
-
- var _utils2 = _interopRequireDefault(_utils);
-
- function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
-
- function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }
-
- /**
- * Timer class to be instantiated on every element.
- * All relative values will be stored at instance level.
- */
- var Timer = function () {
- /**
- * Construct a Timer instance on the provided element with the given config.
- * @param {Object} element HTML node as passed by jQuery
- * @param {Object|String} config User extended options or a string (start, pause, resume etc)
- */
- function Timer(element, config) {
- _classCallCheck(this, Timer);
-
- this.element = element;
- this.originalConfig = $.extend({}, config);
- this.totalSeconds = 0;
- this.intervalId = null;
- // A HTML element will have the html() method in jQuery to inject content,
- this.html = 'html';
- if (element.tagName === 'INPUT' || element.tagName === 'TEXTAREA') {
- // In case of input element or a textarea, jQuery provides the val() method to inject content
- this.html = 'val';
- }
-
- this.config = _utils2.default.getDefaultConfig();
-
- if (config.duration) {
- config.duration = _utils2.default.durationTimeToSeconds(config.duration);
- }
-
- if (typeof config !== 'string') {
- this.config = $.extend(this.config, config);
- }
-
- if (this.config.seconds) {
- this.totalSeconds = this.config.seconds;
- }
-
- if (this.config.editable) {
- _utils2.default.makeEditable(this);
- }
-
- this.startTime = _utils2.default.unixSeconds() - this.totalSeconds;
-
- // In case duration is set along with a callback as well as repeat,
- // then the update frequency needs to be at least 1000ms to prevent callback from being fired more than once
- if (this.config.duration && this.config.repeat && this.config.updateFrequency < 1000) {
- this.config.updateFrequency = 1000;
- }
-
- // If countdown is set, ensure duration is set as well
- // Also set the total seconds to the duration so that the first render gets the correct value
- if (this.config.countdown) {
- if (!this.config.duration) {
- throw new Error('Countdown option set without duration!');
- }
-
- if (this.config.editable) {
- throw new Error('Cannot set editable on a countdown timer!');
- }
- this.config.startTime = _utils2.default.unixSeconds() - this.config.duration;
- this.totalSeconds = this.config.duration;
- }
- }
-
- _createClass(Timer, [{
- key: 'start',
- value: function start() {
- if (this.state !== _constants2.default.TIMER_RUNNING) {
- _utils2.default.setState(this, _constants2.default.TIMER_RUNNING);
- this.render();
- this.intervalId = setInterval(_utils2.default.intervalHandler.bind(null, this), this.config.updateFrequency);
- }
- }
- }, {
- key: 'pause',
- value: function pause() {
- if (this.state === _constants2.default.TIMER_RUNNING) {
- _utils2.default.setState(this, _constants2.default.TIMER_PAUSED);
- clearInterval(this.intervalId);
- }
- }
- }, {
- key: 'resume',
- value: function resume() {
- if (this.state === _constants2.default.TIMER_PAUSED) {
- _utils2.default.setState(this, _constants2.default.TIMER_RUNNING);
- if (this.config.countdown) {
- this.startTime = _utils2.default.unixSeconds() - this.config.duration + this.totalSeconds;
- } else {
- this.startTime = _utils2.default.unixSeconds() - this.totalSeconds;
- }
- this.intervalId = setInterval(_utils2.default.intervalHandler.bind(null, this), this.config.updateFrequency);
- }
- }
- }, {
- key: 'remove',
- value: function remove() {
- clearInterval(this.intervalId);
- $(this.element).data(_constants2.default.PLUGIN_NAME, null);
- }
- }, {
- key: 'reset',
- value: function reset() {
- var element = this.element;
- var originalConfig = this.originalConfig;
- this.remove();
- $(element).timer(originalConfig);
- }
- }, {
- key: 'render',
- value: function render() {
- if (this.config.format) {
- $(this.element)[this.html](_utils2.default.secondsToFormattedTime(this.totalSeconds, this.config.format));
- } else {
- $(this.element)[this.html](_utils2.default.secondsToPrettyTime(this.totalSeconds));
- }
- // Make total seconds available via timer element's data attribute
- $(this.element).data('seconds', this.totalSeconds);
- }
- }]);
-
- return Timer;
- }();
-
- exports.default = Timer;
-
-/***/ },
-/* 2 */
-/***/ function(module, exports) {
-
- 'use strict';
-
- Object.defineProperty(exports, "__esModule", {
- value: true
- });
- var Constants = {
- PLUGIN_NAME: 'timer',
- TIMER_RUNNING: 'running',
- TIMER_PAUSED: 'paused',
- DAYINSECONDS: 86400
- };
-
- exports.default = Constants;
-
-/***/ },
-/* 3 */
-/***/ function(module, exports, __webpack_require__) {
-
- 'use strict';
-
- Object.defineProperty(exports, "__esModule", {
- value: true
- });
-
- var _constants = __webpack_require__(2);
-
- var _constants2 = _interopRequireDefault(_constants);
-
- function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
-
- /**
- * Private
- * Convert (a number) seconds to a Object with days, hours, minutes etc as properties
- * Used by secondsToPrettyTime for to format the time display
- * @param {Number} totalSeconds The total seconds that needs to be distributed into an Object
- * @return {Object} Object with days, hours, minutes, totalMinutes, seconds and totalSeconds
- */
- var _secondsToTimeObj = function _secondsToTimeObj() {
- var totalSeconds = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : 0;
-
- var totalMinutes = Math.floor(totalSeconds / 60);
- return {
- days: totalSeconds >= _constants2.default.DAYINSECONDS ? Math.floor(totalSeconds / _constants2.default.DAYINSECONDS) : 0,
- hours: totalSeconds >= 3600 ? Math.floor(totalSeconds % _constants2.default.DAYINSECONDS / 3600) : 0,
- totalMinutes: totalMinutes,
- minutes: totalSeconds >= 60 ? Math.floor(totalSeconds % 3600 / 60) : totalMinutes,
- seconds: totalSeconds % 60,
- totalSeconds: totalSeconds
- };
+/*! timer.jquery 0.7.0 2017-04-15*/
+(function() {
+var Constants = {
+ PLUGIN_NAME: 'timer',
+ TIMER_RUNNING: 'running',
+ TIMER_PAUSED: 'paused',
+ DAYINSECONDS: 86400
+};
+
+/* global Constants:true */
+/**
+ * Private
+ * Convert (a number) seconds to a Object with days, hours, minutes etc as properties
+ * Used by secondsToPrettyTime for to format the time display
+ * @param {Number} totalSeconds The total seconds that needs to be distributed into an Object
+ * @return {Object} Object with days, hours, minutes, totalMinutes, seconds and totalSeconds
+ */
+function _secondsToTimeObj(totalSeconds) {
+ var totalMinutes;
+ totalSeconds = totalSeconds || 0;
+ totalMinutes = Math.floor(totalSeconds / 60);
+ return {
+ days: totalSeconds >= Constants.DAYINSECONDS ?
+ Math.floor(totalSeconds / Constants.DAYINSECONDS) :
+ 0,
+ hours: totalSeconds >= 3600 ?
+ Math.floor(totalSeconds % Constants.DAYINSECONDS / 3600) :
+ 0,
+ totalMinutes: totalMinutes,
+ minutes: totalSeconds >= 60 ?
+ Math.floor(totalSeconds % 3600 / 60) :
+ totalMinutes,
+ seconds: totalSeconds % 60,
+ totalSeconds: totalSeconds
};
-
- /**
- * Private
- * Method to pad a given number with a 0 in case it's less than 10
- * @param {Number} num The number to be padded
- * @return {String|Number} Padded (if less than 10) number
- */
- /* global $:true */
- var _paddedValue = function _paddedValue(num) {
- num = parseInt(num, 10);
- return (num < 10 && '0') + num;
+}
+
+/**
+ * Private
+ * Method to pad a given number with a 0 in case it's less than 10
+ * @param {Number} num The number to be padded
+ * @return {String|Number} Padded (if less than 10) number
+ */
+function _paddedValue(num) {
+ num = parseInt(num, 10);
+ return (num < 10 && '0') + num;
+}
+
+/**
+ * Method to return the base settings that can be used in case of no or missing options
+ * @return {Object} Default config
+ */
+function getDefaultConfig() {
+ return {
+ seconds: 0, // Default seconds value to start timer from
+ editable: false, // Allow making changes to the time by clicking on it
+ duration: null, // Duration to run callback after
+ callback: function() { // Default callback to run after elapsed duration
+ console.log('Time up!');
+ },
+ repeat: false, // This will repeat callback every n times duration is elapsed
+ countdown: false, // If true, this will render the timer as a countdown (must have duration)
+ format: null, // This sets the format in which the time will be printed
+ updateFrequency: 500 // How often should timer display update
};
+}
+
+/**
+ * @return {Number} Return seconds passed since Jan 1, 1970
+ */
+function unixSeconds() {
+ return Math.round((Date.now ? Date.now() : new Date().getTime()) / 1000);
+}
+
+/**
+ * Convert seconds to pretty time.
+ * For example 100 becomes 1:40 min, 34 becomes 34 sec and 10000 becomes 2:46:40
+ * @param {Number} seconds Seconds to be converted
+ * @return {String} Pretty time
+ */
+function secondsToPrettyTime(seconds) {
+ var timeObj = _secondsToTimeObj(seconds);
+
+ if (timeObj.days) {
+ return timeObj.days + ':' + _paddedValue(timeObj.hours) + ':' +
+ _paddedValue(timeObj.minutes) + ':' + _paddedValue(timeObj.seconds);
+ }
+
+ if (timeObj.hours) {
+ return timeObj.hours +
+ ':' + _paddedValue(timeObj.minutes) +
+ ':' + _paddedValue(timeObj.seconds);
+ }
+
+ var prettyTime = '';
+ if (timeObj.minutes) {
+ prettyTime = timeObj.minutes + ':' + _paddedValue(timeObj.seconds) + ' min';
+ } else {
+ prettyTime = timeObj.seconds + ' sec';
+ }
+
+ return prettyTime;
+}
+
+/**
+ * Convert seconds to user defined format for time
+ * @param {Number} seconds Seconds to be converted
+ * @param {String} formattedTime User defined format
+ * @return {String} Formatted time string
+ */
+function secondsToFormattedTime(seconds, formattedTime) {
+ var timeObj = _secondsToTimeObj(seconds);
+ var formatDef = [
+ {identifier: '%d', value: timeObj.days},
+ {identifier: '%h', value: timeObj.hours},
+ {identifier: '%m', value: timeObj.minutes},
+ {identifier: '%s', value: timeObj.seconds},
+ {identifier: '%g', value: timeObj.totalMinutes},
+ {identifier: '%t', value: timeObj.totalSeconds},
+ {identifier: '%D', value: _paddedValue(timeObj.days)},
+ {identifier: '%H', value: _paddedValue(timeObj.hours)},
+ {identifier: '%M', value: _paddedValue(timeObj.minutes)},
+ {identifier: '%S', value: _paddedValue(timeObj.seconds)},
+ {identifier: '%G', value: _paddedValue(timeObj.totalMinutes)},
+ {identifier: '%T', value: _paddedValue(timeObj.totalSeconds)}
+ ];
+
+ // Use `for` loop to support ie8 after transpilation
+ for (var i = 0; i < formatDef.length; i++) {
+ formattedTime = formattedTime.replace(formatDef[i].identifier, formatDef[i].value);
+ }
+
+ return formattedTime;
+}
+
+/**
+ * Convert duration time format to seconds
+ * @param {String} timeFormat e.g. 5m30s
+ * @return {Number} Returns 330
+ */
+function durationTimeToSeconds(timeFormat) {
+ if (!isNaN(Number(timeFormat))) {
+ return timeFormat; // A number was passed
+ }
+
+ timeFormat = timeFormat.toLowerCase();
+ var days = timeFormat.match(/\d+d/); // Match 10d in 10d5h30m10s
+ var hrs = timeFormat.match(/\d+h/); // Match 5h in 5h30m10s
+ var mins = timeFormat.match(/\d+m/); // Match 30m in 5h30m10s
+ var secs = timeFormat.match(/\d+s/); // Match 10s in 5h30m10s
+
+ if (!days && !hrs && !mins && !secs) {
+ throw new Error('Invalid string passed in durationTimeToSeconds!');
+ }
+
+ var seconds = 0;
+ if (days) {
+ seconds += Number(days[0].replace('d', '')) * Constants.DAYINSECONDS;
+ }
+
+ if (hrs) {
+ seconds += Number(hrs[0].replace('h', '')) * 3600;
+ }
+
+ if (mins) {
+ seconds += Number(mins[0].replace('m', '')) * 60;
+ }
+
+ if (secs) {
+ seconds += Number(secs[0].replace('s', ''));
+ }
+ return seconds;
+}
+
+/**
+ * Parse pretty time and return it as seconds
+ * Currently only the native pretty time is parseable
+ * @param {String} editedTime The time as edited by the user
+ * @return {Number} Parsed time
+ */
+function prettyTimeToSeconds(editedTime) {
+ var arr, time;
+
+ if (editedTime.indexOf('sec') > 0) {
+ time = Number(editedTime.replace(/\ssec/g, ''));
+ } else if (editedTime.indexOf('min') > 0) {
+ editedTime = editedTime.replace(/\smin/g, '');
+ arr = editedTime.split(':');
+ time = Number(arr[0] * 60) + Number(arr[1]);
+ } else if (editedTime.match(/\d{1,2}:\d{2}:\d{2}:\d{2}/)) {
+ arr = editedTime.split(':');
+ time = Number(arr[0] * Constants.DAYINSECONDS) + Number(arr[1] * 3600) +
+ Number(arr[2] * 60) + Number(arr[3]);
+ } else if (editedTime.match(/\d{1,2}:\d{2}:\d{2}/)) {
+ arr = editedTime.split(':');
+ time = Number(arr[0] * 3600) + Number(arr[1] * 60) + Number(arr[2]);
+ }
+
+ return time;
+}
+
+/**
+ * Set the provided state of the timer in the data attr `state` of the timer HTML element
+ * @param {Object} timerInstance Instance of the timer object
+ * @param {[type]} newState The state to be set on the HTML element
+ */
+function setState(timerInstance, newState) {
+ timerInstance.state = newState;
+ $(timerInstance.element).data('state', newState);
+}
+
+/**
+ * Convenience method to wire up focus & blur events to pause and resume
+ * Makes use of the local `prettyTimeToSeconds` function to convert user edited time to seconds
+ * @param {Object} timerInstance Instance of the Timer Class
+ */
+function makeEditable(timerInstance) {
+ $(timerInstance.element).on('focus', function() {
+ timerInstance.pause();
+ });
- /**
- * Method to return the base settings that can be used in case of no or missing options
- * @return {Object} Default config
- */
- var getDefaultConfig = function getDefaultConfig() {
- return {
- seconds: 0, // Default seconds value to start timer from
- editable: false, // Allow making changes to the time by clicking on it
- duration: null, // Duration to run callback after
- callback: function callback() {
- // Default callback to run after elapsed duration
- console.log('Time up!');
- },
- repeat: false, // this will repeat callback every n times duration is elapsed
- countdown: false, // if true, this will render the timer as a countdown (must have duration)
- format: null, // this sets the format in which the time will be printed
- updateFrequency: 500 // How often should timer display update
- };
- };
-
- /**
- * @return {Number} Return seconds passed since Jan 1, 1970
- */
- var unixSeconds = function unixSeconds() {
- return Math.round((Date.now ? Date.now() : new Date().getTime()) / 1000);
- };
-
- /**
- * Convert seconds to pretty time.
- * For example 100 becomes 1:40 min, 34 becomes 34 sec and 10000 becomes 2:46:40
- * @param {Number} seconds Seconds to be converted
- * @return {String} Pretty time
- */
- var secondsToPrettyTime = function secondsToPrettyTime(seconds) {
- var timeObj = _secondsToTimeObj(seconds);
-
- if (timeObj.days) {
- return timeObj.days + ':' + _paddedValue(timeObj.hours) + ':' + _paddedValue(timeObj.minutes) + ':' + _paddedValue(timeObj.seconds);
- }
-
- if (timeObj.hours) {
- return timeObj.hours + ':' + _paddedValue(timeObj.minutes) + ':' + _paddedValue(timeObj.seconds);
- }
-
- var prettyTime = '';
- if (timeObj.minutes) {
- prettyTime = timeObj.minutes + ':' + _paddedValue(timeObj.seconds) + ' min';
- } else {
- prettyTime = timeObj.seconds + ' sec';
- }
-
- return prettyTime;
- };
-
- /**
- * Convert seconds to user defined format for time
- * @param {Number} seconds Seconds to be converted
- * @param {String} formattedTime User defined format
- * @return {String} Formatted time string
- */
- var secondsToFormattedTime = function secondsToFormattedTime(seconds, formattedTime) {
- var timeObj = _secondsToTimeObj(seconds);
- var formatDef = [{ identifier: '%d', value: timeObj.days }, { identifier: '%h', value: timeObj.hours }, { identifier: '%m', value: timeObj.minutes }, { identifier: '%s', value: timeObj.seconds }, { identifier: '%g', value: timeObj.totalMinutes }, { identifier: '%t', value: timeObj.totalSeconds }, { identifier: '%D', value: _paddedValue(timeObj.days) }, { identifier: '%H', value: _paddedValue(timeObj.hours) }, { identifier: '%M', value: _paddedValue(timeObj.minutes) }, { identifier: '%S', value: _paddedValue(timeObj.seconds) }, { identifier: '%G', value: _paddedValue(timeObj.totalMinutes) }, { identifier: '%T', value: _paddedValue(timeObj.totalSeconds) }];
-
- // Use `for` loop to support ie8 after transpilation
- for (var i = 0; i < formatDef.length; i++) {
- formattedTime = formattedTime.replace(formatDef[i].identifier, formatDef[i].value);
- }
-
- return formattedTime;
- };
-
- /**
- * Convert duration time format to seconds
- * @param {String} timeFormat e.g. 5m30s
- * @return {Number} Returns 330
- */
- var durationTimeToSeconds = function durationTimeToSeconds(timeFormat) {
- if (!isNaN(Number(timeFormat))) {
- // A number was passed
- return timeFormat;
- }
-
- timeFormat = timeFormat.toLowerCase();
- var days = timeFormat.match(/\d+d/); // Match 10d in 10d5h30m10s
- var hrs = timeFormat.match(/\d+h/); // Match 5h in 5h30m10s
- var mins = timeFormat.match(/\d+m/); // Match 30m in 5h30m10s
- var secs = timeFormat.match(/\d+s/); // Match 10s in 5h30m10s
-
- if (!days && !hrs && !mins && !secs) {
- throw new Error('Invalid string passed in durationTimeToSeconds!');
- }
-
- var seconds = 0;
- if (days) {
- seconds += Number(days[0].replace('d', '')) * _constants2.default.DAYINSECONDS;
+ $(timerInstance.element).on('blur', function() {
+ timerInstance.totalSeconds = prettyTimeToSeconds(
+ $(timerInstance.element)[timerInstance.html]()
+ );
+ timerInstance.resume();
+ });
+}
+
+/**
+ * The function that will be called via setInterval based on the timer's update frequency
+ * @param {Object} timerInstance Instance of the timer object
+ */
+function intervalHandler(timerInstance) {
+ timerInstance.totalSeconds = unixSeconds() - timerInstance.startTime;
+
+ if (timerInstance.config.countdown) {
+ timerInstance.totalSeconds = timerInstance.config.duration - timerInstance.totalSeconds;
+
+ if (timerInstance.totalSeconds === 0) {
+ clearInterval(timerInstance.intervalId);
+ setState(timerInstance, Constants.TIMER_STOPPED);
+ timerInstance.config.callback();
+ $(timerInstance.element).data('seconds');
}
- if (hrs) {
- seconds += Number(hrs[0].replace('h', '')) * 3600;
+ timerInstance.render();
+ return;
+ }
+
+ timerInstance.render();
+ if (!timerInstance.config.duration) {
+ return;
+ }
+
+ // If the timer was called with a duration parameter,
+ // run the callback if duration is complete
+ // and remove the duration if `repeat` is not requested
+ if (timerInstance.totalSeconds > 0 &&
+ timerInstance.totalSeconds % timerInstance.config.duration === 0) {
+ if (timerInstance.config.callback) {
+ timerInstance.config.callback();
}
- if (mins) {
- seconds += Number(mins[0].replace('m', '')) * 60;
+ if (!timerInstance.config.repeat) {
+ clearInterval(timerInstance.intervalId);
+ setState(timerInstance, Constants.TIMER_STOPPED);
+ timerInstance.config.duration = null;
}
-
- if (secs) {
- seconds += Number(secs[0].replace('s', ''));
+ }
+}
+
+var utils = {
+ getDefaultConfig: getDefaultConfig,
+ unixSeconds: unixSeconds,
+ secondsToPrettyTime: secondsToPrettyTime,
+ secondsToFormattedTime: secondsToFormattedTime,
+ durationTimeToSeconds: durationTimeToSeconds,
+ prettyTimeToSeconds: prettyTimeToSeconds,
+ setState: setState,
+ makeEditable: makeEditable,
+ intervalHandler: intervalHandler
+};
+
+/**
+ * Timer function to initiate a timer on the provided element with the given config.
+ * @param {Object} element HTML node as passed by jQuery
+ * @param {Object|String} config User extended options or a string (start, pause, resume etc)
+ */
+function Timer(element, config) {
+ this.element = element;
+ this.originalConfig = $.extend({}, config);
+ this.totalSeconds = 0;
+ this.intervalId = null;
+ // A HTML element will have the html() method in jQuery to inject content,
+ this.html = 'html';
+ if (element.tagName === 'INPUT' || element.tagName === 'TEXTAREA') {
+ // In case of input element or a textarea, jQuery provides the val() method to inject content
+ this.html = 'val';
+ }
+
+ this.config = utils.getDefaultConfig();
+
+ if (config.duration) {
+ config.duration = utils.durationTimeToSeconds(config.duration);
+ }
+
+ if (typeof config !== 'string') {
+ this.config = $.extend(this.config, config);
+ }
+
+ if (this.config.seconds) {
+ this.totalSeconds = this.config.seconds;
+ }
+
+ if (this.config.editable) {
+ utils.makeEditable(this);
+ }
+
+ this.startTime = utils.unixSeconds() - this.totalSeconds;
+
+ // In case duration is set along with a callback as well as repeat,
+ // then the update frequency needs to be at least 1000ms to prevent callback from being fired more than once
+ if (this.config.duration && this.config.repeat && this.config.updateFrequency < 1000) {
+ this.config.updateFrequency = 1000;
+ }
+
+ // If countdown is set, ensure duration is set as well
+ // Also set the total seconds to the duration so that the first render gets the correct value
+ if (this.config.countdown) {
+ if (!this.config.duration) {
+ throw new Error('Countdown option set without duration!');
}
- return seconds;
- };
- /**
- * Parse pretty time and return it as seconds
- * Currently only the native pretty time is parseable
- * @param {String} editedTime The time as edited by the user
- * @return {Number} Parsed time
- */
- var prettyTimeToSeconds = function prettyTimeToSeconds(editedTime) {
- var arr = void 0;
- var time = void 0;
-
- if (editedTime.indexOf('sec') > 0) {
- time = Number(editedTime.replace(/\ssec/g, ''));
- } else if (editedTime.indexOf('min') > 0) {
- editedTime = editedTime.replace(/\smin/g, '');
- arr = editedTime.split(':');
- time = Number(arr[0] * 60) + Number(arr[1]);
- } else if (editedTime.match(/\d{1,2}:\d{2}:\d{2}:\d{2}/)) {
- arr = editedTime.split(':');
- time = Number(arr[0] * _constants2.default.DAYINSECONDS) + Number(arr[1] * 3600) + Number(arr[2] * 60) + Number(arr[3]);
- } else if (editedTime.match(/\d{1,2}:\d{2}:\d{2}/)) {
- arr = editedTime.split(':');
- time = Number(arr[0] * 3600) + Number(arr[1] * 60) + Number(arr[2]);
+ if (this.config.editable) {
+ throw new Error('Cannot set editable on a countdown timer!');
}
-
- return time;
- };
-
- /**
- * Set the provided state of the timer in the data attr `state` of the timer HTML element
- * @param {Object} timerInstance Instance of the timer object
- * @param {[type]} newState The state to be set on the HTML element
- */
- var setState = function setState(timerInstance, newState) {
- timerInstance.state = newState;
- $(timerInstance.element).data('state', newState);
- };
-
- /**
- * Convenience method to wire up focus & blur events to pause and resume
- * Makes use of the local `prettyTimeToSeconds` function to convert user edited time to seconds
- * @param {Object} timerInstance Instance of the Timer Class
- */
- var makeEditable = function makeEditable(timerInstance) {
- $(timerInstance.element).on('focus', function () {
- timerInstance.pause();
- });
-
- $(timerInstance.element).on('blur', function () {
- timerInstance.totalSeconds = prettyTimeToSeconds($(timerInstance.element)[timerInstance.html]());
- timerInstance.resume();
- });
- };
-
- /**
- * The function that will be called via setInterval based on the timer's update frequency
- * @param {Object} timerInstance Instance of the timer object
- */
- var intervalHandler = function intervalHandler(timerInstance) {
- timerInstance.totalSeconds = unixSeconds() - timerInstance.startTime;
-
- if (timerInstance.config.countdown) {
- timerInstance.totalSeconds = timerInstance.config.duration - timerInstance.totalSeconds;
-
- if (timerInstance.totalSeconds === 0) {
- clearInterval(timerInstance.intervalId);
- setState(timerInstance, _constants2.default.TIMER_STOPPED);
- timerInstance.config.callback();
- $(timerInstance.element).data('seconds');
- }
-
- timerInstance.render();
- return;
+ this.config.startTime = utils.unixSeconds() - this.config.duration;
+ this.totalSeconds = this.config.duration;
+ }
+}
+
+Timer.prototype.start = function() {
+ if (this.state !== Constants.TIMER_RUNNING) {
+ utils.setState(this, Constants.TIMER_RUNNING);
+ this.render();
+ this.intervalId = setInterval(utils.intervalHandler.bind(null, this), this.config.updateFrequency);
+ }
+};
+
+Timer.prototype.pause = function() {
+ if (this.state === Constants.TIMER_RUNNING) {
+ utils.setState(this, Constants.TIMER_PAUSED);
+ clearInterval(this.intervalId);
+ }
+};
+
+Timer.prototype.resume = function() {
+ if (this.state === Constants.TIMER_PAUSED) {
+ utils.setState(this, Constants.TIMER_RUNNING);
+ if (this.config.countdown) {
+ this.startTime = utils.unixSeconds() - this.config.duration + this.totalSeconds;
+ } else {
+ this.startTime = utils.unixSeconds() - this.totalSeconds;
}
-
- timerInstance.render();
- if (!timerInstance.config.duration) {
- return;
+ this.intervalId = setInterval(utils.intervalHandler.bind(null, this), this.config.updateFrequency);
+ }
+};
+
+Timer.prototype.remove = function() {
+ clearInterval(this.intervalId);
+ $(this.element).data(Constants.PLUGIN_NAME, null);
+ $(this.element).data('seconds', null);
+};
+
+Timer.prototype.reset = function() {
+ var originalConfig = this.originalConfig;
+ this.remove();
+ $(this.element).timer(originalConfig);
+};
+
+Timer.prototype.render = function() {
+ if (this.config.format) {
+ $(this.element)[this.html](utils.secondsToFormattedTime(this.totalSeconds, this.config.format));
+ } else {
+ $(this.element)[this.html](utils.secondsToPrettyTime(this.totalSeconds));
+ }
+ $(this.element).data('seconds', this.totalSeconds);
+};
+
+/* global $:true */
+$.fn.timer = function(options) {
+ options = options || 'start';
+
+ return this.each(function() {
+ if (!($.data(this, Constants.PLUGIN_NAME) instanceof Timer)) {
+ /**
+ * Create a new data attribute on the element to hold the plugin name
+ * This way we can know which plugin(s) is/are initialized on the element later
+ */
+ $.data(this, Constants.PLUGIN_NAME, new Timer(this, options));
}
- // If the timer was called with a duration parameter,
- // run the callback if duration is complete
- // and remove the duration if `repeat` is not requested
- if (timerInstance.totalSeconds > 0 && timerInstance.totalSeconds % timerInstance.config.duration === 0) {
- if (timerInstance.config.callback) {
- timerInstance.config.callback();
- }
+ /**
+ * Use the instance of this plugin derived from the data attribute for this element
+ * to conduct whatever action requested as a string parameter.
+ */
+ var instance = $.data(this, Constants.PLUGIN_NAME);
- if (!timerInstance.config.repeat) {
- clearInterval(timerInstance.intervalId);
- setState(timerInstance, _constants2.default.TIMER_STOPPED);
- timerInstance.config.duration = null;
+ /**
+ * Provision for calling a function from this plugin
+ * without initializing it all over again
+ */
+ if (typeof options === 'string') {
+ if (typeof instance[options] === 'function') {
+ // Pass in 'instance' to provide for the value of 'this' in the called function
+ instance[options]();
}
+ } else {
+ instance.start();
}
- };
-
- exports.default = {
- getDefaultConfig: getDefaultConfig,
- unixSeconds: unixSeconds,
- secondsToPrettyTime: secondsToPrettyTime,
- secondsToFormattedTime: secondsToFormattedTime,
- durationTimeToSeconds: durationTimeToSeconds,
- prettyTimeToSeconds: prettyTimeToSeconds,
- setState: setState,
- makeEditable: makeEditable,
- intervalHandler: intervalHandler
- };
-
-/***/ }
-/******/ ]);
\ No newline at end of file
+ });
+};
+} ());
\ No newline at end of file
diff --git a/dist/timer.jquery.min.js b/dist/timer.jquery.min.js
index 0de479a..63dc6cc 100644
--- a/dist/timer.jquery.min.js
+++ b/dist/timer.jquery.min.js
@@ -1 +1 @@
-/*! timer.jquery 0.6.4 2017-03-22*/!function(a){function b(d){if(c[d])return c[d].exports;var e=c[d]={exports:{},id:d,loaded:!1};return a[d].call(e.exports,e,e.exports,b),e.loaded=!0,e.exports}var c={};return b.m=a,b.c=c,b.p="",b(0)}([function(a,b,c){"use strict";function d(a){return a&&a.__esModule?a:{"default":a}}var e=c(1),f=d(e),g=c(2),h=d(g);!function(){$.fn.timer=function(a){return a=a||"start",this.each(function(){$.data(this,h["default"].PLUGIN_NAME)instanceof f["default"]||$.data(this,h["default"].PLUGIN_NAME,new f["default"](this,a));var b=$.data(this,h["default"].PLUGIN_NAME);"string"==typeof a?"function"==typeof b[a]&&b[a]():b.start()})}}()},function(a,b,c){"use strict";function d(a){return a&&a.__esModule?a:{"default":a}}function e(a,b){if(!(a instanceof b))throw new TypeError("Cannot call a class as a function")}Object.defineProperty(b,"__esModule",{value:!0});var f=function(){function a(a,b){for(var c=0;c0&&void 0!==arguments[0]?arguments[0]:0,b=Math.floor(a/60);return{days:a>=f["default"].DAYINSECONDS?Math.floor(a/f["default"].DAYINSECONDS):0,hours:a>=3600?Math.floor(a%f["default"].DAYINSECONDS/3600):0,totalMinutes:b,minutes:a>=60?Math.floor(a%3600/60):b,seconds:a%60,totalSeconds:a}},h=function(a){return a=parseInt(a,10),(a<10&&"0")+a},i=function(){return{seconds:0,editable:!1,duration:null,callback:function(){console.log("Time up!")},repeat:!1,countdown:!1,format:null,updateFrequency:500}},j=function(){return Math.round((Date.now?Date.now():(new Date).getTime())/1e3)},k=function(a){var b=g(a);if(b.days)return b.days+":"+h(b.hours)+":"+h(b.minutes)+":"+h(b.seconds);if(b.hours)return b.hours+":"+h(b.minutes)+":"+h(b.seconds);var c="";return c=b.minutes?b.minutes+":"+h(b.seconds)+" min":b.seconds+" sec"},l=function(a,b){for(var c=g(a),d=[{identifier:"%d",value:c.days},{identifier:"%h",value:c.hours},{identifier:"%m",value:c.minutes},{identifier:"%s",value:c.seconds},{identifier:"%g",value:c.totalMinutes},{identifier:"%t",value:c.totalSeconds},{identifier:"%D",value:h(c.days)},{identifier:"%H",value:h(c.hours)},{identifier:"%M",value:h(c.minutes)},{identifier:"%S",value:h(c.seconds)},{identifier:"%G",value:h(c.totalMinutes)},{identifier:"%T",value:h(c.totalSeconds)}],e=0;e0?c=Number(a.replace(/\ssec/g,"")):a.indexOf("min")>0?(a=a.replace(/\smin/g,""),b=a.split(":"),c=Number(60*b[0])+Number(b[1])):a.match(/\d{1,2}:\d{2}:\d{2}:\d{2}/)?(b=a.split(":"),c=Number(b[0]*f["default"].DAYINSECONDS)+Number(3600*b[1])+Number(60*b[2])+Number(b[3])):a.match(/\d{1,2}:\d{2}:\d{2}/)&&(b=a.split(":"),c=Number(3600*b[0])+Number(60*b[1])+Number(b[2])),c},o=function(a,b){a.state=b,$(a.element).data("state",b)},p=function(a){$(a.element).on("focus",function(){a.pause()}),$(a.element).on("blur",function(){a.totalSeconds=n($(a.element)[a.html]()),a.resume()})},q=function(a){return a.totalSeconds=j()-a.startTime,a.config.countdown?(a.totalSeconds=a.config.duration-a.totalSeconds,0===a.totalSeconds&&(clearInterval(a.intervalId),o(a,f["default"].TIMER_STOPPED),a.config.callback(),$(a.element).data("seconds")),void a.render()):(a.render(),void(a.config.duration&&a.totalSeconds>0&&a.totalSeconds%a.config.duration===0&&(a.config.callback&&a.config.callback(),a.config.repeat||(clearInterval(a.intervalId),o(a,f["default"].TIMER_STOPPED),a.config.duration=null))))};b["default"]={getDefaultConfig:i,unixSeconds:j,secondsToPrettyTime:k,secondsToFormattedTime:l,durationTimeToSeconds:m,prettyTimeToSeconds:n,setState:o,makeEditable:p,intervalHandler:q}}]);
\ No newline at end of file
+!function(){function a(a){var b;return a=a||0,b=Math.floor(a/60),{days:a>=m.DAYINSECONDS?Math.floor(a/m.DAYINSECONDS):0,hours:a>=3600?Math.floor(a%m.DAYINSECONDS/3600):0,totalMinutes:b,minutes:a>=60?Math.floor(a%3600/60):b,seconds:a%60,totalSeconds:a}}function b(a){return((a=parseInt(a,10))<10&&"0")+a}function c(){return{seconds:0,editable:!1,duration:null,callback:function(){console.log("Time up!")},repeat:!1,countdown:!1,format:null,updateFrequency:500}}function d(){return Math.round((Date.now?Date.now():(new Date).getTime())/1e3)}function e(c){var d=a(c);if(d.days)return d.days+":"+b(d.hours)+":"+b(d.minutes)+":"+b(d.seconds);if(d.hours)return d.hours+":"+b(d.minutes)+":"+b(d.seconds);return d.minutes?d.minutes+":"+b(d.seconds)+" min":d.seconds+" sec"}function f(c,d){for(var e=a(c),f=[{identifier:"%d",value:e.days},{identifier:"%h",value:e.hours},{identifier:"%m",value:e.minutes},{identifier:"%s",value:e.seconds},{identifier:"%g",value:e.totalMinutes},{identifier:"%t",value:e.totalSeconds},{identifier:"%D",value:b(e.days)},{identifier:"%H",value:b(e.hours)},{identifier:"%M",value:b(e.minutes)},{identifier:"%S",value:b(e.seconds)},{identifier:"%G",value:b(e.totalMinutes)},{identifier:"%T",value:b(e.totalSeconds)}],g=0;g0?c=Number(a.replace(/\ssec/g,"")):a.indexOf("min")>0?(a=a.replace(/\smin/g,""),b=a.split(":"),c=Number(60*b[0])+Number(b[1])):a.match(/\d{1,2}:\d{2}:\d{2}:\d{2}/)?(b=a.split(":"),c=Number(b[0]*m.DAYINSECONDS)+Number(3600*b[1])+Number(60*b[2])+Number(b[3])):a.match(/\d{1,2}:\d{2}:\d{2}/)&&(b=a.split(":"),c=Number(3600*b[0])+Number(60*b[1])+Number(b[2])),c}function i(a,b){a.state=b,$(a.element).data("state",b)}function j(a){$(a.element).on("focus",function(){a.pause()}),$(a.element).on("blur",function(){a.totalSeconds=h($(a.element)[a.html]()),a.resume()})}function k(a){if(a.totalSeconds=d()-a.startTime,a.config.countdown)return a.totalSeconds=a.config.duration-a.totalSeconds,0===a.totalSeconds&&(clearInterval(a.intervalId),i(a,m.TIMER_STOPPED),a.config.callback(),$(a.element).data("seconds")),void a.render();a.render(),a.config.duration&&a.totalSeconds>0&&a.totalSeconds%a.config.duration==0&&(a.config.callback&&a.config.callback(),a.config.repeat||(clearInterval(a.intervalId),i(a,m.TIMER_STOPPED),a.config.duration=null))}function l(a,b){if(this.element=a,this.originalConfig=$.extend({},b),this.totalSeconds=0,this.intervalId=null,this.html="html","INPUT"!==a.tagName&&"TEXTAREA"!==a.tagName||(this.html="val"),this.config=n.getDefaultConfig(),b.duration&&(b.duration=n.durationTimeToSeconds(b.duration)),"string"!=typeof b&&(this.config=$.extend(this.config,b)),this.config.seconds&&(this.totalSeconds=this.config.seconds),this.config.editable&&n.makeEditable(this),this.startTime=n.unixSeconds()-this.totalSeconds,this.config.duration&&this.config.repeat&&this.config.updateFrequency<1e3&&(this.config.updateFrequency=1e3),this.config.countdown){if(!this.config.duration)throw new Error("Countdown option set without duration!");if(this.config.editable)throw new Error("Cannot set editable on a countdown timer!");this.config.startTime=n.unixSeconds()-this.config.duration,this.totalSeconds=this.config.duration}}var m={PLUGIN_NAME:"timer",TIMER_RUNNING:"running",TIMER_PAUSED:"paused",DAYINSECONDS:86400},n={getDefaultConfig:c,unixSeconds:d,secondsToPrettyTime:e,secondsToFormattedTime:f,durationTimeToSeconds:g,prettyTimeToSeconds:h,setState:i,makeEditable:j,intervalHandler:k};l.prototype.start=function(){this.state!==m.TIMER_RUNNING&&(n.setState(this,m.TIMER_RUNNING),this.render(),this.intervalId=setInterval(n.intervalHandler.bind(null,this),this.config.updateFrequency))},l.prototype.pause=function(){this.state===m.TIMER_RUNNING&&(n.setState(this,m.TIMER_PAUSED),clearInterval(this.intervalId))},l.prototype.resume=function(){this.state===m.TIMER_PAUSED&&(n.setState(this,m.TIMER_RUNNING),this.config.countdown?this.startTime=n.unixSeconds()-this.config.duration+this.totalSeconds:this.startTime=n.unixSeconds()-this.totalSeconds,this.intervalId=setInterval(n.intervalHandler.bind(null,this),this.config.updateFrequency))},l.prototype.remove=function(){clearInterval(this.intervalId),$(this.element).data(m.PLUGIN_NAME,null),$(this.element).data("seconds",null)},l.prototype.reset=function(){var a=this.originalConfig;this.remove(),$(this.element).timer(a)},l.prototype.render=function(){this.config.format?$(this.element)[this.html](n.secondsToFormattedTime(this.totalSeconds,this.config.format)):$(this.element)[this.html](n.secondsToPrettyTime(this.totalSeconds)),$(this.element).data("seconds",this.totalSeconds)},$.fn.timer=function(a){return a=a||"start",this.each(function(){$.data(this,m.PLUGIN_NAME)instanceof l||$.data(this,m.PLUGIN_NAME,new l(this,a));var b=$.data(this,m.PLUGIN_NAME);"string"==typeof a?"function"==typeof b[a]&&b[a]():b.start()})}}();
\ No newline at end of file
diff --git a/index.html b/index.html
deleted file mode 100644
index a63f8cc..0000000
--- a/index.html
+++ /dev/null
@@ -1,365 +0,0 @@
-
-
-
- jQuery timer plugin | Start an editable pretty timer inside any HTML element
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
jQuery Timer
-
-
Lightweight, well tested jQuery pretty timer plugin
-
Start, Pause, Resume and Remove a timer inside any HTML element.
-
Get notified at a set time or at regular intervals.
Download the jQuery timer plugin and put it in a SCRIPT tag in your HTML page after jQuery itself.
-
-
Start a timer:
-
-
$('#divId').timer(); //Same as $('#divId').timer('start')
-
-
Start at a particular time:
-
-
$('#divId').timer({
- seconds: 100 //Specify start time in seconds
-});
-
-
Pause:
-
-
$('#divId').timer('pause');
-
-
Resume:
-
-
$('#divId').timer('resume');
-
-
Remove Timer:
-
-
$('#divId').timer('remove');
-
-
Get number of seconds:
-
-
$('#divId').data('seconds');
-
-
Get notified:
-
-
-//start a timer & execute a function in 5 minutes & 30 seconds
-$('#divId').timer({
- duration: '5m30s',
- callback: function() {
- alert('Time up!');
- }
-});
-
-
-
Get notified repeatedly:
-
-
-//start a timer & execute a function every 2 minutes
-$('#divId').timer({
- duration: '2m',
- callback: function() {
- alert('Why, Hello there');
- },
- repeat: true //repeatedly calls the callback you specify
-});
-
-
-
Repeat callback & reset timer:
-
-
-//start a timer & execute a function every 30 seconds and then reset the timer at the end of 30 seconds.
-$('#divId').timer({
- duration: '30s',
- callback: function() {
- console.log('Timer will reset!');
- $('#divId').timer('reset');
- },
- repeat: true //repeatedly call the callback
-});
-
-
-
- Format:
- By default the timer will display a pretty output (30 sec OR 1:06). You can change this format if you like.
-
-
-
// Show a digital timer instead of pretty timer:
-$('#divId').timer({
- format: '%H:%M:%S' Display time as 00:00:00
-});
-
-// OR
-$('#divId').timer({
- format: '%h:%m:%s' Display time as 0:0:0
-});
-
-// OR
-$('#divId').timer({
- format: '%M minutes %s seconds' Display time as 3 minutes 45 seconds
-});
-
-
-
Update frequency: By default the timer display updates every 500ms to show an accurate update of time. You can change this by specifying the update frequency in milliseconds.
-
-
$('#divId').timer({
- updateFrequency: 2000 // Update the timer display every 2 seconds.
-});