DEV Community

bulldo.gs
bulldo.gs

Posted on Edited on Originally published at bulldo.gs

Fix "Exceeded maximum execution time" in Apps Script

Originally written for bulldo.gs — republished here with the canonical link pointing home.

I'm running a script that processes a large spreadsheet and it keeps dying with "Exceeded maximum execution time" before it finishes.

// Bound to a practice spreadsheet. The only write is one document property.
function processInBatches() {
  const sheet = SpreadsheetApp.getActiveSpreadsheet().getSheetByName('Batch practice');
  if (!sheet) throw new Error('Create a tab named Batch practice and add values in A2:A.');
  const lock = LockService.getDocumentLock();
  if (!lock.tryLock(1000)) return;
  try {
    const props = PropertiesService.getDocumentProperties();
    const key = 'batchPractice.zeros.v1.' + sheet.getSheetId();
    const saved = props.getProperty(key);
    const state = saved ? JSON.parse(saved) : {next: 2, last: sheet.getLastRow(), zeros: 0};
    if (state.next <= state.last) {
      const count = Math.min(3, state.last - state.next + 1);
      const rows = sheet.getRange(state.next, 1, count, 1).getValues();
      state.zeros += rows.filter(row => row[0] === 0).length;
      state.next += count;
      props.setProperty(key, JSON.stringify(state));
    }
    console.log((state.next > state.last ? 'Complete' : 'Continue at row ' + state.next) +
      ' | numeric zeros: ' + state.zeros);
  } finally {
    lock.releaseLock();
  }
}
Enter fullscreen mode Exit fullscreen mode

A row inserted between runs can leave the count looking correct

Add a second column named record to your private practice sheet. In rows 2 through 7, enter the following pairs.

Value in A Record in B
4 A
6 B
0 C
8 D
2 E
0 F

Run the three-row worker above once. It reads A, B and C and saves row 5 as its next position. Now insert one row immediately above row 2. Give it value 9 and record X. Run the worker a second time.

Tested in Apps Script First three records Next three records Logged zero count
Original sheet left alone A, B, C D, E, F 2
X inserted before the second run A, B, C C, D, E 2

Both execution logs said Complete. In the edited sheet, C moved to row 5 and F moved past the saved last row. The repeated C and missing F cancelled each other out in the total. A document lock only covers the individual script execution. A person can still insert a row between runs.

If the job should process the original six records, copy the input values to a separate tab before starting and leave that copy unchanged for the whole batch. For a queue that must stay editable, give each record a unique, stable ID and track which IDs have been processed. When testing a change, compare those IDs alongside the final count.

Try a different insertion

Choose Insert X before D, then Run both batches. Compare the resumed IDs, zero count and missing ID with the first two cases. You can change the source values in the editor or download the single HTML file to use in your own lesson.

Open the editable simulation in LiveCodes

The 6-minute wall is per-execution, not per-task

Google lists six minutes per ordinary script execution for both consumer and Google Workspace accounts. Trigger executions also share a separate daily runtime allowance per user: 90 minutes for consumer accounts and six hours for Workspace accounts. A custom function in a cell has its own 30-second execution limit.

To try a checkpoint, make a new spreadsheet with a tab named Batch practice. Enter a header in A1, then the numbers 0, 5, 0, 3 and 0 in A2:A6. In Extensions → Apps Script, paste the code and run processInBatches. The first execution log says “Continue at row 5 | numeric zeros: 2”. Run it again for “Complete | numeric zeros: 3”. A third run keeps the count at three. The example leaves your cells unchanged.

Saving and restoring a cursor with PropertiesService

The example saves the next row, the last row in the original input and the running total together in one document property. A document lock prevents two executions of this script from advancing the same checkpoint concurrently. Keep the input values and row order fixed while the job is running. A fresh spreadsheet or newly created practice tab starts a fresh count.

Google currently lists 9 KB per property value and 500 KB for a property store. Keep a small checkpoint there and keep large input or output in your sheet. If execution stops before the checkpoint is saved, the same batch can be counted again from its previous total. A stop after it is saved resumes from the next row.

The practice run is manual. For an ongoing job you can install a time-driven trigger for the worker, set a batch size appropriate to the work and monitor its execution history. Keep the identity of any trigger you create so its installer can remove just that trigger when the job ends.

Batch your reads first — it often eliminates the problem

Calls to spreadsheet services can cost much more time than comparisons in memory. Read a rectangular batch with getValues(), process the returned array locally, and group any output writes when the result permits. Measure the duration on your actual sheet.

The practice worker reads just three rows per run so that you can see the checkpoint advance. In production the suitable batch size depends on the number of columns, formulas and other calls. Leave room for slow requests and an interruption before the next checkpoint.

FAQ

Does the 6-minute limit reset if I call Utilities.sleep()?

Sleeping consumes time in the same execution. Resume in a later execution to obtain another per-execution window; other service and daily quotas still apply.

Will a Workspace (paid) account give me more than 6 minutes?

No. Google's current table lists six minutes per ordinary script execution for both account types. The higher six-hour figure for Google Workspace is the daily total runtime of triggers, not the duration of one execution.

How do I delete the trigger when the job finishes?

This example creates no trigger. If you installed one yourself, open Triggers in that Apps Script project under its installer account, identify the exact trigger and remove it when appropriate. Google’s daily trigger-runtime limits are 90 minutes for consumer accounts and six hours for Workspace accounts.

My script writes results back to the sheet — how do I avoid writing duplicates on resume?

A checkpoint and a spreadsheet write are separate operations. If a run stops after the output is written but before its checkpoint is saved, the same batch can run again. For fixed input rows, replacing the same output cells with the same values can make replay harmless. An append, email or other external action needs its own deduplication or reconciliation.

Google’s current Apps Script quotas · Google’s batching guidance

Correction, December 1, 2026. An AI-assisted review of Google’s quota table confirmed a six-minute limit per ordinary script execution for both consumer and Workspace accounts. The revised example saves its place before the execution ends.


Want the plain-English version? Describe the automation at bulldo.gs and get working Apps Script back — free, no login.

When the timeout comes from a formula in a Sheet

A formula calling a custom Apps Script function has its own 30-second limit. If each row calls the script independently, try passing the row inputs together as one rectangle. A shared setting can still be a separate argument.

In a six-row review schedule you can reproduce, the scalar formula takes requested minutes, covered minutes and a shared slot length. Its range version takes the two columns and the same slot length. Both kept missing requests blank and returned a real zero when no additional slot was needed.

The bound project's Executions page showed six scalar invocations and one range invocation when the formulas were entered. Changing the shared setting produced the same counts again. A reserved cell in the output area produced #REF! in the Sheet and kept its text. Moving that obstruction restored the results. The counts describe this fixture; we did not measure a speedup. Google’s custom-function guide explains how Sheets passes ranges to the script.

Top comments (0)