Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
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
You can’t perform that action at this time.