Stop onEdit from chasing your own writes

TL;DR — Your batch job writes by row number while an installable onEdit auto-sorts or cascades on human edits, and the two collide. Raise a short-lived ‘script is writing’ flag, have onEdit stand down, and let the flag expire on its own if the job crashes. Plus a soft NitroGAS note for the script-write-guard snippet.

The sheet has two pieces of automation. An installable onEdit keeps Orders sorted by date and stamps “Last touched” when someone changes a row. A nightly job, or a “Rebuild statuses” menu item, rewrites column F for 400 rows by row number.

Most days they never meet. Then someone edits a row at 9:02 while the rebuild is running. onEdit re-sorts the tab, and the rebuild keeps writing to row 212, which is now a completely different order. Nothing throws. The data is just wrong.

TL;DR

  • Your script’s own setValue / setValues don’t fire onEdit. The collision comes from people editing while the script is mid-batch
  • Raise a short-lived “script is writing” flag before the batch, lower it in finally
  • onEdit checks the flag and returns early, optionally with a toast saying why
  • The flag lives in CacheService with a TTL, so a crashed job can’t keep onEdit off forever
  • Snippet: script-write-guard (beginScriptWrite / endScriptWrite / isScriptWriting)

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.

First, the myth

A lot of us add guards because we think this loops:

function onEditInstalled(e) { e.range.offset(0, 1).setValue(new Date()); // does this re-trigger onEdit? No. }

It doesn’t. Apps Script doesn’t fire triggers for changes made by scripts or the Sheets API. So if your onEdit writes to the sheet, you don’t get a loop.

What you do get is two writers working on the same rows at the same time:

  • A batch job (time-driven or menu) writing by position
  • onEdit automation reacting to humans: sorting, moving rows to another tab, deleting “Done” rows, cascading values

onEdit isn’t chasing the script’s writes. It’s reacting to a human edit in the middle of them, and that’s enough to wreck positional writes.

What not to do

  • Don’t try to detect “was this edit made by the script?” inside onEdit; script edits never reach it
  • Don’t use a Script Property as the flag with no expiry; one crash and onEdit is off until someone notices
  • Don’t make the job wait for people to stop editing; you can’t control that, but you can control onEdit
  • Don’t rely on the flag alone for must-never-collide jobs; add a lock (see below)

The pattern

// Job: raise the flag, do the work, ALWAYS lower it function rebuildStatuses() { beginScriptWrite(300); // a bit longer than the job usually takes try { var sheet = SpreadsheetApp.getActive().getSheetByName('Orders'); var values = sheet.getDataRange().getValues(); var statuses = values.slice(1).map(function (r) { return [deriveStatus_(r)]; }); sheet.getRange(2, 6, statuses.length, 1).setValues(statuses); SpreadsheetApp.flush(); } finally { endScriptWrite(); } } // Installable onEdit: stand down while the job runs function onEditInstalled(e) { if (isScriptWriting()) { e.source.toast('A background update is running. Sorting will resume in a moment.', 'Heads up', 5); return; } stampLastTouched_(e); sortOrdersByDate_(e.range.getSheet()); }

The three helpers are tiny. The script-write-guard snippet has the full code:

function beginScriptWrite(ttlSeconds) { var ttl = Math.max(1, Math.min(ttlSeconds || 120, 21600)); writeGuardCache_().put(SCRIPT_WRITE_KEY_, '1', ttl); } function endScriptWrite() { writeGuardCache_().remove(SCRIPT_WRITE_KEY_); } function isScriptWriting() { return writeGuardCache_().get(SCRIPT_WRITE_KEY_) === '1'; }

Why CacheService and not Script Properties?

The TTL is the whole safety story. If the job hits the 6-minute limit, Apps Script stops it and your finally never runs. A Property-based flag would stay true forever and your onEdit silently stops working. A cache entry expires. Worst case, onEdit is quiet for the length of the TTL, then everything goes back to normal on its own.

getDocumentCache() scopes the flag to this spreadsheet (bound scripts). Standalone scripts fall back to the script cache.

What about the edit that got skipped?

When onEdit stands down, that human edit doesn’t get its sort or timestamp. Usually that’s fine: the next edit sorts everything anyway. If every edit must be handled, record it instead of dropping it:

if (isScriptWriting()) { // Remember the row; the job (or the next onEdit) catches up. // (Not atomic: two edits in the same instant can overwrite each other. Fine for a nudge list.) var cache = CacheService.getDocumentCache(); var pending = JSON.parse(cache.get('pendingEdits') || '[]'); pending.push(e.range.getRow()); cache.put('pendingEdits', JSON.stringify(pending.slice(-200)), 600); return; }

Then have the job process pendingEdits right after endScriptWrite().

Belt and braces: add a lock

CacheService is best-effort. Google can evict entries early under pressure. If the two writers must never overlap, also take the document lock in both places:

function onEditInstalled(e) { if (isScriptWriting()) return; var lock = LockService.getDocumentLock(); if (!lock.tryLock(2000)) return; // job holds it: skip this edit try { sortOrdersByDate_(e.range.getSheet()); } finally { lock.releaseLock(); } }

The job takes getDocumentLock().waitLock(30000) around its writes. The flag gives you the friendly toast; the lock is the hard guarantee.

Better still: stop writing by position

The flag fixes the collision. The root cause is that the job assumes row 212 is still row 212. If you can, have the job write by a key (order id → row lookup right before writing) instead of by remembered row numbers. Then a mid-run sort can’t send values to the wrong row. Map columns by header, not by letter is the same idea for columns.

Failure modes worth naming

  • TTL too short: the flag expires mid-job and onEdit wakes up. Set it comfortably longer than the job’s normal run.
  • TTL too long + crash: onEdit stays quiet for the rest of the TTL. Keep it minutes, not hours.
  • Multiple jobs share one flag: one job’s endScriptWrite lowers it while the other is still running. Give each job its own key if they overlap.
  • Simple onEdit vs installable: both can check the flag (CacheService works in simple triggers). The sort/move logic usually needs installable anyway.
  • People confused why sorting “stopped”: the toast explains it. Mention it in your team notes too.

Soft Co-Pilot note

NitroGAS keeps the script-write-guard helpers a search away in the editor. Paste your batch job and your onEdit, and Co-Pilot can add the begin / try / finally / end wrapper plus the early return and toast. You still pick the TTL and test with a teammate editing mid-run. Free core; Co-Pilot is a pass you grab when you want the draft.

Closing checklist

  • Batch job raises the flag and lowers it in finally
  • TTL a bit longer than the job’s usual run
  • onEdit returns early (with a toast) while the flag is up
  • Lock added if collisions must never happen
  • Longer term: job writes by key, not by remembered row number

Happy Coding!