withUserLock Helper

Document locks serialize everyone on a spreadsheet. User locks only serialize the same user's overlapping runs — handy for personal quotas, user-property writes, or add-ons where each account should not block others.

What you'll need

  • A critical section that is per-user (not shared sheet state)
  • Contrast with withDocumentLock when contention is the bound spreadsheet

How to use this snippet

function withUserLock(fn, waitMs) { waitMs = waitMs || 30000; var lock = LockService.getUserLock(); if (!lock.tryLock(waitMs)) { throw new Error('Could not acquire user lock within ' + waitMs + 'ms'); } try { return fn(); } finally { lock.releaseLock(); } } function bumpPersonalCounter() { return withUserLock(function () { var props = PropertiesService.getUserProperties(); var n = Number(props.getProperty('runs') || '0') + 1; props.setProperty('runs', String(n)); return n; }); }

Tips:

  • Same try/finally shape as document lock — don't skip releaseLock on errors.
  • For project-wide contention in standalone scripts, use LockService.getScriptLock() the same way.

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