Time Step

A 400-line main() that "just feels slow," and no idea whether the fetch, the sheet write, or the PDF export is the culprit. timeStep(name, fn) runs one named step, logs how many milliseconds it took, and returns the step's result. Pair it with underTimeBudget so a long job can stop cleanly before the 6-minute wall.

When to use

  • Splitting a giant function into named steps and seeing which one dominates
  • Logging step timings next to underTimeBudget checkpoints
  • Handing Co-Pilot a slow script with real numbers instead of "it's slow"

How to use this snippet

/** * Run one named step, log its duration in ms, return its result. * Re-throws after logging if the step fails. * * @param {string} name * @param {function(): *} fn * @return {*} */ function timeStep(name, fn) { var label = name == null ? 'step' : String(name); var t0 = Date.now(); try { var result = fn(); console.log('[timeStep] ' + label + ': ' + (Date.now() - t0) + 'ms'); return result; } catch (e) { console.log('[timeStep] ' + label + ': ' + (Date.now() - t0) + 'ms (error)'); throw e; } }

Example

function runNightly() { var started = new Date(); var rows = timeStep('loadRows', function () { return loadPending_(); }); var enriched = timeStep('fetchApi', function () { return fetchDetails_(rows); }); timeStep('writeSheet', function () { writeResults_(enriched); return null; }); console.log('total ' + (Date.now() - started.getTime()) + 'ms'); } // [timeStep] loadRows: 180ms // [timeStep] fetchApi: 4120ms // [timeStep] writeSheet: 640ms

Tips:

  • The log line is [timeStep] name: Nms. Failed steps log (error) and re-throw, so a try/catch outside still works.
  • Wrap each logical chunk once. Timing every tiny helper just adds noise.
  • Combine with underTimeBudget(started) between steps when the job might overrun and need a checkpoint.

Tip: paste a slow main() into NitroGAS Co-Pilot and ask it to wrap each section in timeStep with plain-English names.

Happy Coding!

NitroGAS Chrome Extension

Want this snippet handy inside the Apps Script editor? NitroGAS gives you free snippets — plus optional Co-Pilot when you want a boost (Day Pass — $3, or 1-week, 1-month, or yearly passes — no subscription). Happy Coding!

Get the Extension