Add Cancel to a long menu job

TL;DR — Give teammates a Cancel control for long Apps Script menu jobs: a tiny HtmlService sidebar button, a CacheService cancel flag, and loop checks alongside underTimeBudget so the job stops cleanly and checkpoints.

Someone starts Process visible rows from the menu. Three minutes later the filter was wrong. Closing the browser tab does nothing useful — the server-side execution keeps going until the ~6-minute wall. You want a Cancel they can click, and a job that notices within one row.

The pieces are small: a CacheService cancel flag, a loop that checks it (next to your time budget), and a tiny sidebar button that calls requestCancel. You already know the sidebar shape from Build a tiny HtmlService sidebar your teammates will actually click.

TL;DR

Using the Apps Script editor a lot? NitroGAS drops free themes & snippets right into script.google.com — optional Co-Pilot when you want a boost.

What not to do

  • Don’t invent a new cancel key per run — the button won’t find the job
  • Don’t spin on isCancelRequested in a tight empty loop; check once per unit of work
  • Don’t skip clearCancel in finally — a stuck flag cancels the next run instantly
  • Don’t promise “stops immediately”; promise “stops after the current row”
  • Don’t build a 15-file SPA for one button — see the tiny-sidebar guide

The pattern

1. The flag helpers

From the cancel-flag snippet:

var JOB_KEY = 'processVisible'; function cancelProcessVisible() { requestCancel(JOB_KEY); SpreadsheetApp.getActive().toast( 'Cancel requested — stopping after the current row.', 'Cancel', 5 ); }

requestCancel / isCancelRequested / clearCancel live in CacheService (document cache when bound). A TTL keeps a crashed UI from leaving Cancel stuck on forever.

2. The job loop respects Cancel and the clock

function processVisibleRows() { clearCancel(JOB_KEY); // don't inherit a stale Cancel var started = new Date(); var stoppedReason = 'done'; try { var sheet = SpreadsheetApp.getActiveSheet(); var rows = getVisibleRowObjects(sheet); // or your own row list var i = 0; for (; i < rows.length; i++) { if (isCancelRequested(JOB_KEY)) { stoppedReason = 'cancel'; break; } if (!underTimeBudget(started)) { stoppedReason = 'budget'; break; } processOne_(rows[i]); // one UrlFetch / one write unit markDone_(sheet, rows[i]); } stampStatus_(stoppedReason, i, rows.length); } finally { clearCancel(JOB_KEY); } } function stampStatus_(reason, done, total) { var msg = reason === 'done' ? 'OK: ' + done + ' rows' : reason === 'cancel' ? 'Cancelled after ' + done + ' of ' + total : 'Partial (time budget) ' + done + ' of ' + total; SpreadsheetApp.getActive().toast(msg, 'Process visible', 8); // Also write msg to a Status cell / Log tab if ops don't watch toasts }

underTimeBudget defaults to ~5.5 minutes so you still have time to stamp and unlock under the ~6-minute hard stop.

3. A Cancel control humans will click

Minimum viable: a second menu item. Better: the same tiny sidebar you use for the job.

function onOpen() { SpreadsheetApp.getUi() .createMenu('Ops') .addItem('Process visible rows', 'processVisibleRows') .addItem('Open controls', 'showProcessSidebar') .addToUi(); } function showProcessSidebar() { var html = HtmlService.createHtmlOutput( '<div style="font:14px/1.4 sans-serif;padding:12px">' + '<p>Runs over the rows your filter is showing.</p>' + '<button onclick="google.script.run.processVisibleRows()">Start</button> ' + '<button onclick="google.script.run.cancelProcessVisible()">Cancel</button>' + '<p id="msg" style="color:#64748b"></p>' + '</div>' ).setTitle('Process visible'); SpreadsheetApp.getUi().showSidebar(html); }

Polish (status text via includeHtml, disabling Start while running) belongs in the HtmlService sidebar guide. Ship the two buttons first.

Checkpoint when you stop early

Cancel and budget exits should leave the sheet honest:

  • Rows already processed stay marked done
  • Remaining rows stay pending for the next run
  • Status says Cancelled after 40 of 200 or Partial (time budget), not a silent half-write

If the job takes a lock (LockService), release it in the same finally that clears the cancel flag.

Soft Co-Pilot note

NitroGAS has requestCancel, underTimeBudget, and the HtmlService helpers ready to search. Paste your existing menu job and ask Co-Pilot for a sidebar with Start/Cancel plus the loop checks — then flame-test Cancel on a 50-row dry run before ops sees it. Free core; Co-Pilot is a pass when you want the draft.

Closing checklist

  • Stable JOB_KEY shared by UI and job
  • Loop checks isCancelRequested and underTimeBudget between units of work
  • clearCancel in finally (and at start of a fresh run)
  • Toast / Status distinguishes done vs cancelled vs time budget
  • Sidebar or menu Cancel is obvious; copy says “after the current row”
  • Lock released on every exit path

Happy Coding!