From a8d80e819122fd947b10346ece2fff0ab106fd77 Mon Sep 17 00:00:00 2001 From: dgramlich Date: Wed, 10 Jul 2013 10:41:03 -0400 Subject: [PATCH] Initial commit --- README.md | 21 +++++++++++++++++++++ console-time.js | 49 +++++++++++++++++++++++++++++++++++++++++++++++++ 2 files changed, 70 insertions(+) create mode 100644 README.md create mode 100644 console-time.js diff --git a/README.md b/README.md new file mode 100644 index 0000000..fc4ab39 --- /dev/null +++ b/README.md @@ -0,0 +1,21 @@ +console.time polyfill +===================== + +Lightweight and simple polyfill for `console.time()` and `console.timeEnd()` + +## Example usage: + +``` +# Start the timer by passing it a key +console.time('myTimer'); + +# Call timeEnd later to see how long an operation took +setTimeout(function() { + console.timeEnd('myTimer'); +}, 2000); + +# It should then log out something like like.. +# myTimer: 2000ms +``` + +For more information on `console.time()` visit [MDN] (https://developer.mozilla.org/en-US/docs/Web/API/console.time). \ No newline at end of file diff --git a/console-time.js b/console-time.js new file mode 100644 index 0000000..700db37 --- /dev/null +++ b/console-time.js @@ -0,0 +1,49 @@ +;(function( console ) { + + 'use strict'; + + var timers; + + // do we have access to the console + // or does time method already exist? + if ( !console || console.time ) { + return; + } + + + // table of current timers + timers = {}; + + + /** + * Stores current time in milliseconds + * in the timers map + * + * @param {string} timer name + * @return {void} + */ + console.time = function( name ) { + if ( name ) { + timers[ name ] = Date.now(); + } + }; + + + /** + * Finds difference between when this method + * was called and when the respective time method + * was called, then logs out the difference + * and deletes the original record + * + * @param {string} timer name + * @return {void} + */ + console.timeEnd = function( name ) { + if ( timers[ name ] ) { + console.log( name + ': ' + (Date.now() - timers[ name ]) + 'ms' ); + delete timers[ name ]; + } + }; + + +}( window.console )); \ No newline at end of file