diff --git a/src/debug.js b/src/debug.js index c1fad6bd..7d3c0d57 100644 --- a/src/debug.js +++ b/src/debug.js @@ -160,6 +160,37 @@ function createDebug(namespace) { return section; }; + debug.time = function () { + var args = [].slice.call(arguments); + if (args.length < 2) { + throw new Error('debug.time() takes at least a debug string and a function'); + } + + var fn = args.pop(); + if (typeof fn !== 'function') { + throw new Error('the last argument to debug.time() must be a function'); + } + + var isPromise = false; + var section = debug.begin.apply(debug, args); + try { + var result = fn(); + + if (typeof Promise === 'function' && result instanceof Promise) { // eslint-disable-line no-undef + isPromise = true; + result.then(function () { + section.end(); + }); + } + + return result; + } finally { + if (!isPromise) { + section.end(); + } + } + }; + // env-specific initialization logic for debug instances if ('function' === typeof exports.init) { exports.init(debug); diff --git a/test/debug_spec.js b/test/debug_spec.js index 52b1177f..d0243609 100644 --- a/test/debug_spec.js +++ b/test/debug_spec.js @@ -82,6 +82,18 @@ describe('debug', function () { expect(log.log).to.have.been.calledThrice; }); + + it('times a critical function', function () { + log.log = sinon.spy(); + + var result = log.time('a critical function', function () { + log('hello from inside'); + return 1234; + }); + + expect(result).to.equal(1234); + expect(log.log).to.have.been.calledThrice; + }); }); }); });