A simplified control diagram: running can pause and resume, while both running and paused tasks can be cancelled. Cancelled has no outgoing transition

Imagine a batch task saving a page of media. One video is still transferring when someone clicks Pause. A moment later, they click Cancel and start another task. The old request finally resolves. Should it save a file, update the new progress bar, or quietly stop?

This article was prepared with AI assistance and checked against a local source snapshot. The diagrams are AI-generated conceptual illustrations.

This walkthrough uses the batch-download implementation in ExtMax, an instagram downloader for Chrome, as a concrete example. The focus is the ordinary profile-download path that writes individual files, using accessible media the user owns or has permission to save.

The reviewed source identifies itself as version 1.1.6; that does not establish which version is currently in the extension store. ZIP export, viewer batches, and incremental tracking have additional behavior. The examples below explain selected mechanisms rather than reproducing the entire extension.

Start with the boundary, not the button

A control is only useful if its meaning survives an asynchronous operation. In this implementation, three responsibilities are separated:

  • The profile task discovers pages, checks pagination, and selects media.
  • The sequential downloader acquires and saves each selected item.
  • A save session checks task validity and coordinates the destination.

The progress service exposes pause, resume, and cancel controls, but those controls do not magically interrupt every promise. The working code must consult them.

The profile loop checks a boundary before requesting a page and again after the response. That second check matters: the user may pause, cancel, or navigate while the request is pending. A valid response is not sufficient permission to start saving its contents.

The task also awaits the current page's downloads before requesting the next page. This makes it easier to reason about which work has started. It is sequential within this path, not a claim that the whole extension has only one active job.

Pause means holding future work

The ordinary pause policy is cooperative. At a file boundary, the save session waits while the shared pause flag is set. It also waits if the selected directory is blocked.

An already-acquired file may finish writing during an ordinary pause. The custom-directory writer checks cancellation between chunks, but does not stop each chunk merely because the user pressed Pause. This avoids treating a routine pause as a failed partial write.

The media acquisition helper uses fetch without a task cancellation signal. Therefore, neither Pause nor Cancel should be described as immediately stopping all network traffic. A request can still finish; later checks decide whether its result may advance through the save path.

That distinction belongs in the product's wording. “Hold the next item” sets a more accurate expectation than “freeze everything instantly.” A completed file appearing after a pause can be consistent with that policy.

Cancel must outlive a boolean reset

A single cancellation boolean becomes fragile when tasks overlap in time. Cancel sets it to true, a new job resets it, and an old callback wakes up after the reset. The callback can mistake the new state for permission to continue.

The progress service also maintains a monotonically increasing cancellationVersion. Each save session captures the version when it starts. Cancel increments the shared value. The older session remains invalid even if a new job clears the boolean.

Here is a small TypeScript model of the idea. It is an illustrative rewrite, not a drop-in source extract:

class Control { epoch = 0; paused = false; pause() { this.paused = true; } resume() { this.paused = false; } cancel() { this.epoch++; this.paused = false; } } function checkpointFor(control: Control, isCurrent: () => boolean) { const epoch = control.epoch; const assertAlive = () => { if (epoch !== control.epoch || !isCurrent()) { throw new Error("TASK_INVALIDATED"); } }; return async () => { assertAlive(); while (control.paused) { await new Promise(resolve => setTimeout(resolve, 250)); assertAlive(); } assertAlive(); }; } 

Create the checkpoint when the task starts, not afresh for every item. Otherwise, an old task could capture a newer epoch and lose its identity.

Production checks additionally cover session closure, route validity, directory blocks, and account or quota conditions. The profile's progress callbacks also check the captured version and current page before changing counts. Cancellation is a validity rule, not a rollback of files already saved.

Resume has to check what is blocking progress

A user pause and a permission problem can both look like a stopped queue. They are not the same condition.

The save session records recoverable directory problems such as lost permission or insufficient space. Resume attempts the registered checks. A failed check keeps that block in place; clearing the user-pause flag alone does not make the directory usable.

The resume routine captures the cancellation version before awaiting those checks. If cancellation happens while a check is pending, the old resume attempt cannot subsequently clear the pause state of a newer run.

This is also why a simple three-state diagram is only a teaching aid. The implementation uses a shared pause flag, cancellation generation, and a map of blocked tasks. It is not literally a single running | paused | cancelled enum. Those controls belong to the shared progress service in the content-script context, not an independent switch on every file.

A simplified sequence from page discovery through a checkpoint, media fetch, file save, and receipt, with another check before the next item.

Separate acquisition retries from save retries

Fetching bytes and committing a file have different failure consequences. Repeating a fetch generally acquires another copy in memory. Repeating a save after a lost acknowledgement can create another file.

In the reviewed downloadSingle implementation, acquisition allows one retry after a 1.5-second delay. Saving happens outside that retry loop. Some callers also stop immediately on specific access-denial responses. That policy should not be generalized to every request or download mode.

This reduced example shows the separation. The supplied save function is responsible for validating the task and returning only after an appropriate save acknowledgement:

async function acquireThenSave<T>( acquire: () => Promise<Blob>, save: (blob: Blob) => Promise<T>, ): Promise<T> { let blob: Blob; try { blob = await acquire(); } catch { await new Promise(resolve => setTimeout(resolve, 1500)); blob = await acquire(); } return save(blob); // Outside the acquisition retry scope. } 

This omits production error classification, settings, conversion, and destination logic. It demonstrates where the retry boundary belongs, not a complete retry policy.

The custom-directory protocol gives each write operation an identifier. If the commit acknowledgement is lost, the client asks for its status. A confirmed commit can be accepted without resubmitting the file. An unresolved outcome stays uncertain. For a confirmed uncommitted write, the client can abort that operation and hold the acquired blob for an explicit recovery attempt.

An uncertain result deserves its own status. Treating it as an ordinary failure and automatically trying again hides precisely the information needed to avoid duplicate writes.

Progress should describe outcomes

In the ordinary sequential profile path, a successful save advances the completed count. A fetched blob alone does not. For receipt-tracked browser downloads, the receipt helper watches the specific download ID for completion or interruption. Custom-directory writes use their commit response.

The total is discovered as pages arrive and media filtering is applied. It is not necessarily known at the beginning. Post counts are also not file counts: a carousel can contribute several media items.

The sequential helper records ordinary acquisition failures and can continue with later items. Save errors propagate instead of being silently treated as another network miss. A failed page request can stop discovery, leaving the remaining scope unknown.

The report model distinguishes file problems, unread sources or pages, and uncertain saves. Successful saves do not erase those issues. The progress component also preserves actual completed and total counts at normal termination rather than manufacturing 100 percent.

Counters still need clear units. Optional covers and ZIP volumes complicate reporting, so the progress count should not be presented as an exact count of every file in a folder. Those extra paths need their own accounting rules.

Keep resume separate from incremental downloading

Resuming a paused task continues its existing execution. It does not, by itself, inspect the download folder or provide durable recovery after a tab closes.

Within the profile task, media IDs are deduplicated during the current run, and repeated or inconsistent pagination cursors are rejected. These protect against duplicate discovery and broken pagination. They do not establish that a matching file already exists on disk.

The current repository also contains separate history and incremental-tracking code. It has its own eligibility checks and saved-position logic. That feature should not be inferred from the presence of a Resume button, nor should a normal rerun be described as automatically skipping everything previously downloaded.

Test the moments between operations

The most useful cases place a control change while an asynchronous operation is pending:

  1. Pause after a page response and confirm that files wait without repeating that page request.
  2. Cancel after a response or during the page delay and confirm that no further work starts.
  3. Pause during a directory write: the current file finishes, while the next boundary waits.
  4. Lose directory permission, then verify that a failed recovery check does not resume writing.
  5. Lose a commit acknowledgement and confirm that status is checked without saving a duplicate.

For this walkthrough, the existing profile-download, save-directory, and batch-report test files were run locally: 58 tests passed. They use fixtures and mocked browser or network interfaces; these results are not a live Instagram download test or a guarantee about the store release.

A further regression case worth keeping explicit is cancel, start a new job, then release an old callback. The expected behavior is that the old job cannot change the new job's counts. That expectation follows from the generation guards described above; it is not presented here as an additional executed end-to-end test.

Reliable queue controls depend on precise boundaries: where work may wait, where a task becomes invalid, and where a save becomes confirmed. Those boundaries give the buttons a meaning that survives slow requests, lost permissions, and late responses.