Skip to content

Instantly share code, notes, and snippets.

@jakebellacera
Created February 27, 2014 22:45
Show Gist options
  • Star 4 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save jakebellacera/9261266 to your computer and use it in GitHub Desktop.
Save jakebellacera/9261266 to your computer and use it in GitHub Desktop.
CSS Time to Milliseconds - useful for timing functions around CSS animations
/*
* CSS Time to Milliseconds
* by Jake Bellacera (http://jakebellacera.com)
* ============================================
*
* Converts CSS time into milliseconds. Useful for timing functions around CSS animations.
* It supports both seconds (s) and milliseconds (ms).
*
* Arguments:
* time_string - string representation of a CSS time unit (e.g. "1500ms" or "1.5s")
*
* Returns:
* Time (in milliseconds) as an Integer. Invalid inputs will return 0 milliseconds.
*
* Example:
* var miliseconds = css_time_to_milliseconds(myELement.style.transitionDuration);
*
* setTimeout(function () {
* alert('Animation complete!');
* }, milliseconds);
*/
function css_time_to_milliseconds(time_string) {
var num = parseFloat(time_string, 10),
unit = time_string.match(/m?s/),
milliseconds;
if (unit) {
unit = unit[0];
}
switch (unit) {
case "s": // seconds
milliseconds = num * 1000;
break;
case "ms": // milliseconds
milliseconds = num;
break;
default:
milliseconds = 0;
break;
}
return milliseconds;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment