Skip to content

Instantly share code, notes, and snippets.

@rauchg
Created December 21, 2011 00:25
Show Gist options
  • Select an option

  • Save rauchg/1503944 to your computer and use it in GitHub Desktop.

Select an option

Save rauchg/1503944 to your computer and use it in GitHub Desktop.
Milliseconds conversion utility.
@phloe
Copy link
Copy Markdown

phloe commented Dec 21, 2011

ms('5ms') // 5000

...and by 5000 you mean 5 :P

well seconds where left out?

_.ms = 1;
_.s = 1000;
_.m = _.s * 60;

@isaacs
Copy link
Copy Markdown

isaacs commented Dec 21, 2011

Or maybe by ms you should mean s. I'd expect "5ms" to mean "5 milliseconds", or 5, but 5s to be 5 seconds or 5000.

@rauchg
Copy link
Copy Markdown
Author

rauchg commented Dec 21, 2011

sorry I meant 5s

@rauchg
Copy link
Copy Markdown
Author

rauchg commented Dec 21, 2011

I added ms as well

@WebReflection
Copy link
Copy Markdown

nice one but I would do few changes here

(function (R) {
var _ = {ms:1, s:1000};
_.m = _.s * 60;
_.h = _.m * 60;
_.d = _.h * 24;

function ms (s) {
if (s == Number(s)) return Number(s);
if (/(\d*.?\d+)([mshd]+)/.test(s.toLowerCase()) && R.$2 in _) return R.$1 * _[R.$2];
throw new Error('Unknown time unit: ' + R.$2);
}

if ('object' == typeof window) {
window.ms = ms;
} else {
module.exports = ms;
}
})(RegExp);

ms(".5s");

cheers

@MoOx
Copy link
Copy Markdown

MoOx commented Dec 21, 2011

Do you seriously use setTimeout(fn, ms('2d')); ??

@WebReflection
Copy link
Copy Markdown

it can be used as cronjob scheduler for node.js so why not ...

@rauchg
Copy link
Copy Markdown
Author

rauchg commented Dec 21, 2011

Made a few changes.

  • Shorter (@WebReflection)
  • Works with '.5s' type strings (@WebReflection)
  • Cached the regular expression
  • Returns NaN instead of throwing. More consistent with other number manipulation functions

@DTrejo
Copy link
Copy Markdown

DTrejo commented Dec 21, 2011

+1 Just tried to require this but was not in npm!
Please publish :)
D

@rauchg
Copy link
Copy Markdown
Author

rauchg commented Dec 21, 2011

Published to npm as ms

@tubalmartin
Copy link
Copy Markdown

This is my lighter version: https://gist.github.com/1997544
Same output as original :)
BTW, the function is very useful indeed, thanks mate!

@rauchg
Copy link
Copy Markdown
Author

rauchg commented Mar 8, 2012

@tubalmartin Thanks for the contribution! Unfortunately, it fails two tests. I moved everything to a repository here for you to fork:
https://github.com/guille/ms.js

@tubalmartin
Copy link
Copy Markdown

@guille Thanks for the tests, I'll run them and try to fix those failing!

@tubalmartin
Copy link
Copy Markdown

@guille Pull request made. It passes all tests now :)
https://github.com/tubalmartin/ms.js

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