Answers / Question 18

Apps Script “Exceeded maximum execution time”: make the loop fast, then let it resume itself

Why Google Apps Script stops at 6 minutes, how batching getValues/setValues usually fixes it, and a tested script that pauses before the limit, saves its place and carries on by itself.

The problem

A script that loops over your sheet worked fine on 200 rows. Now the sheet has a few thousand, and the run stops part-way with Exceeded maximum execution time. Some rows got done, the rest didn't, and running it again either starts over from the top or doesn't get any further.

Inspired by a public question on Stack Overflow. The problem above is described in our own words and the solution below is ours.

Why it stops

Every Apps Script run gets 6 minutes. That's the same for a free Gmail account and for Google Workspace, and it applies to runs from the editor, a menu, a button or a trigger. A custom function used in a cell gets only 30 seconds. When the time is up, the run is cut off wherever it is. Anything already written to the sheet stays written, which is why you end up with half a job.

The usual cause isn't the amount of work but the number of calls to the spreadsheet. Each getValue(), setValue() or appendRow() is a round trip that can take a noticeable fraction of a second. Three of them per row across a few thousand rows is enough to hit the wall.

Fix 1: read and write in blocks (try this first)

Read the whole range once with getValues(), do the work on the array in memory, and write the results back once with setValues(). A loop like this one is the classic slow pattern:

Before: three spreadsheet calls per row (slow)Apps Script
function addTotals() {
  const sheet = SpreadsheetApp.getActive().getSheetByName('Orders');
  for (let r = 2; r <= sheet.getLastRow(); r++) {
    const qty = sheet.getRange(r, 2).getValue();
    const price = sheet.getRange(r, 3).getValue();
    sheet.getRange(r, 6).setValue(qty * price);
  }
}
After: one read and one write in totalApps Script
// After: one read and one write for the whole column, instead of three calls per row.
function addTotals() {
  const sheet = SpreadsheetApp.getActive().getSheetByName('Orders');
  const n = sheet.getLastRow() - 1;          // data rows below the header
  if (n < 1) return;
  const rows = sheet.getRange(2, 1, n, 3).getValues();             // A:C in one call
  const totals = rows.map(function (r) { return [(Number(r[1]) || 0) * (Number(r[2]) || 0)]; });
  sheet.getRange(2, 6, n, 1).setValues(totals);                    // F in one call
}

The same goes for other services: build one array and write it once instead of calling appendRow() in a loop, use UrlFetchApp.fetchAll() instead of one fetch() per row, and remove SpreadsheetApp.flush() and Utilities.sleep() from inside loops unless you really need them. This alone often turns a 6-minute run into a few seconds.

Fix 2: a job that pauses and resumes by itself

If the work per row is genuinely slow (sending emails, calling an API, creating files), batching isn't enough. Split the job across several runs instead. The script below works through the tab in blocks, and after 4.5 minutes it saves the next row number, schedules itself to run again a minute later and stops. Each new run picks up at the saved row. When the last row is done it clears its checkpoint and deletes its own trigger.

  1. Extensions → Apps Script, paste the code, and set the tab name and output column in JOB.
  2. Put your own per-row work in processRow_. The example multiplies column B by column C.
  3. Select startJob in the toolbar and press Run once. Approve the permissions (it needs them to create its own trigger).
  4. Watch progress under Executions in the left sidebar. To cancel part-way, run stopJob.
Code.gsApps Script
/**
 * Long job without "Exceeded maximum execution time".
 * Processes a tab in blocks, stops well before the 6-minute limit,
 * remembers the next row and schedules itself to carry on.
 * Run startJob() once. Everything else happens on its own.
 */
const JOB = {
  sheet: 'Orders',             // tab to process
  firstRow: 2,                 // first data row (row 1 = headers)
  outCol: 6,                   // column the result is written to (6 = F)
  batchSize: 200,              // rows read and written per block
  maxMillis: 4.5 * 60 * 1000   // pause after 4.5 minutes (limit is 6)
};

// Your per-row work. Gets one row as an array (A = row[0]) and returns
// the value to write in JOB.outCol. Keep it safe to run twice on a row.
function processRow_(row) {
  const qty = Number(row[1]) || 0;    // column B
  const price = Number(row[2]) || 0;  // column C
  return qty * price;
}

function startJob() {
  PropertiesService.getDocumentProperties().setProperty('JOB_NEXT_ROW', String(JOB.firstRow));
  removeJobTriggers_();
  return continueJob();
}

function continueJob() {
  const started = Date.now();
  const props = PropertiesService.getDocumentProperties();
  const sheet = SpreadsheetApp.getActive().getSheetByName(JOB.sheet);
  if (!sheet) throw new Error('No tab named "' + JOB.sheet + '"');
  let next = Number(props.getProperty('JOB_NEXT_ROW') || JOB.firstRow);
  const last = sheet.getLastRow();
  const width = Math.max(sheet.getLastColumn(), JOB.outCol);

  while (next <= last) {
    if (Date.now() - started > JOB.maxMillis) {
      scheduleNextRun_();
      return 'paused at row ' + next;
    }
    const n = Math.min(JOB.batchSize, last - next + 1);
    const rows = sheet.getRange(next, 1, n, width).getValues();      // one read per block
    const out = rows.map(function (r) { return [processRow_(r)]; });
    sheet.getRange(next, JOB.outCol, n, 1).setValues(out);           // one write per block
    next += n;
    props.setProperty('JOB_NEXT_ROW', String(next));                 // checkpoint after each block
  }

  props.deleteProperty('JOB_NEXT_ROW');
  removeJobTriggers_();
  return 'done';
}

function scheduleNextRun_() {
  removeJobTriggers_();
  ScriptApp.newTrigger('continueJob').timeBased().after(60 * 1000).create();
}

function removeJobTriggers_() {
  ScriptApp.getProjectTriggers()
    .filter(function (t) { return t.getHandlerFunction() === 'continueJob'; })
    .forEach(function (t) { ScriptApp.deleteTrigger(t); });
}

// Run this to cancel a job part-way: removes the trigger and the checkpoint.
function stopJob() {
  removeJobTriggers_();
  PropertiesService.getDocumentProperties().deleteProperty('JOB_NEXT_ROW');
}

Good to know

The script's logic is unit-tested against a simulated spreadsheet before publishing. Always try new automations on a copy of your sheet first.