Autosaving After Five Seconds Without Overwriting Newer Work

Editorial illustration.

Originally published 23 June 2023; rewritten and reviewed on 15 October 2026.

A form quietly saves while someone types. Then a slow response from an earlier request arrives after a later edit, and the page announces “Saved.” The user closes the tab, assuming their last paragraph made it to the database, only to discover the next morning that the newer edit vanished.

Writing a five-second timer in JavaScript takes ten lines. The hard part is making sure the UI status matches what the server actually stored, especially when connections stall on a train or a user edits faster than the server responds.

Use inactivity and a revision counter together

A debounce waits until input has been quiet for a chosen interval. Five seconds is a practical product choice for long-form admin screens—short enough that a browser crash loses little, long enough that you are not hammering the database on every keystroke.

However, a debounce alone does not protect you from out-of-order network responses. If request #1 fires at 10:00:05 and hangs for four seconds, while the user types again at 10:00:06 and triggers request #2, request #1 might resolve after request #2 was already queued. Tracking a monotonically increasing clientRevision on the client lets the UI ignore stale acknowledgements:

const form = document.querySelector('#article-form');
const statusEl = document.querySelector('#save-status');
let timer;
let revision = 0;
let activeController = null;

form.addEventListener('input', () => {
  const requestedRevision = ++revision;
  statusEl.textContent = 'Unsaved changes…';
  clearTimeout(timer);

  timer = setTimeout(async () => {
    if (activeController) activeController.abort();
    activeController = new AbortController();

    const payload = new FormData(form);
    payload.set('clientRevision', String(requestedRevision));
    statusEl.textContent = 'Saving draft…';

    try {
      const response = await fetch(form.action, {
        method: 'POST',
        body: payload,
        credentials: 'same-origin',
        signal: activeController.signal
      });

      if (response.status === 409) {
        if (requestedRevision === revision) {
          statusEl.textContent = 'Newer version exists on server. Please reload.';
        }
        return;
      }

      if (!response.ok) throw new Error(`HTTP ${response.status}`);

      const result = await response.json();
      if (requestedRevision === revision) {
        const rowVersionInput = form.querySelector('input[name="RowVersion"]');
        if (rowVersionInput && result.rowVersion) {
          rowVersionInput.value = result.rowVersion;
        }
        statusEl.textContent = `Draft saved at ${new Date().toLocaleTimeString()}`;
      }
    } catch (err) {
      if (err.name === 'AbortError') return;
      if (requestedRevision === revision) {
        statusEl.textContent = 'Autosave failed. Use Save Draft to retry.';
      }
    }
  }, 5000);
});

Notice two details here. First, FormData(form) automatically picks up the hidden __RequestVerificationToken rendered by @Html.AntiForgeryToken() in ASP.NET MVC, so you do not have to manually extract and attach headers unless you switch to JSON payloads. Second, statusEl should have role="status" and aria-live="polite" in your Razor view so assistive technologies announce state changes without interrupting typing.

Give the server a real conflict policy

Client-side revision numbers only stop the browser from lying to the user. They do not stop a stale tab from overwriting a newer row in SQL Server. If an editor opens the same record in two browser tabs, edits Tab A, switches to Tab B an hour later, and triggers an autosave, Tab B will happily clobber Tab A unless the server enforces optimistic concurrency.

In Entity Framework or Dapper, attach a RowVersion ([Timestamp] public byte[] RowVersion { get; set; }) or an explicit integer Version column to your entity and pass it through a hidden field in the form. When the autosave action runs:

[HttpPost]
[ValidateAntiForgeryToken]
public async Task<IActionResult> AutosaveDraft(ArticleDraftInput input)
{
    var article = await _db.Articles.FindAsync(input.Id);
    if (article == null) return NotFound();

    // Reject stale tabs before touching any fields
    if (!article.RowVersion.SequenceEqual(Convert.FromBase64String(input.RowVersion)))
    {
        return Conflict(new { message = "Record was modified elsewhere." });
    }

    article.Title = input.Title;
    article.Body = input.Body;
    article.UpdatedAtUtc = DateTime.UtcNow;

    await _db.SaveChangesAsync();

    return Ok(new
    {
        rowVersion = Convert.ToBase64String(article.RowVersion)
    });
}

Returning the fresh rowVersion in the JSON response and updating the hidden input on the page is critical. Without that step, the second autosave five seconds later would still carry the old RowVersion and trigger a false 409 Conflict against itself.

Also separate draft validation from publish validation. A user pausing halfway through a form might not have picked a category or uploaded a thumbnail yet. If your [HttpPost] action runs the full PublishViewModel data annotations on every autosave, half of your autosaves will silently fail with 400 Bad Request. Keep a permissive ArticleDraftInput for drafts and enforce strict required fields only on the explicit Publish endpoint.

Preserve a manual recovery route

Never treat autosave as a replacement for an explicit Save Draft button. When a user hits a dead Wi-Fi zone or gets a 502 Bad Gateway during a deployment, they need a visible button they can click once the connection returns—and that manual click should clearTimeout(timer) so an old queued timer does not fire right after.

Be honest about browser-close events too. Relying on beforeunload to fire an async fetch is unreliable across mobile browsers and aggressive tab-discarding policies. If a user types for three seconds and immediately closes the tab, navigator.sendBeacon has size limits and cannot handle complex 409 conflict responses cleanly. The safer contract is straightforward: show Unsaved changes… immediately on input, and only show Draft saved after the server confirms the write.

Before shipping, test three cases manually in DevTools: throttle the network to “Slow 3G” and type across multiple 5-second boundaries, open the same record in two tabs to verify the 409 path, and toggle “Offline” mid-edit to confirm the error state gives the user a working way to recover.