Sync Event Lifecycle and Timing
What you'll learn: How and when sync events fire, how browsers retry them, and how to properly signal completion with Promises.
When you register a sync event with registration.sync.register('my-tag'), you don't control exactly when it fires—the browser does. Understanding this lifecycle is crucial for reliable background operations.
When Sync Events Fire
After registration, the browser typically fires the sync event almost immediately if the device is online. If offline, the browser waits until connectivity returns, then triggers the event.
Think of it like ordering food delivery: you place the order (register), but the delivery (sync event) only happens when conditions are right—the restaurant needs to be open and accessible.
Browser Retry Logic
Here's the critical part: your sync event handler must return a Promise. This Promise tells the browser whether the sync succeeded or failed:
- Promise resolves: Sync completed successfully—browser won't retry
- Promise rejects: Sync failed—browser will automatically retry later
The browser uses exponential backoff for retries: short delays at first, then progressively longer waits. After several failures (exact number varies by browser), it eventually gives up.
// In your service worker
self.addEventListener('sync', event => {
if (event.tag === 'send-message') {
event.waitUntil(
sendQueuedMessages() // Must return a Promise
.then(() => console.log('Sync succeeded'))
.catch(err => {
console.error('Sync failed, will retry', err);
throw err; // Reject to trigger retry
})
);
}
});
Always wrap your sync logic in event.waitUntil() so the browser keeps the service worker alive until your Promise settles.
Key Takeaway: Sync events fire when the browser determines connectivity is available, use Promise resolution/rejection to control retry behavior, and rely on the browser's automatic exponential backoff for resilience.