Alarms API

Schedule background tasks in browser extensions with reliable timing that survives context unloading

What Is the Alarms API?

The Alarms API provides a powerful mechanism for browser extensions to schedule code execution at specific times or at regular intervals. Unlike standard JavaScript timing functions such as setTimeout() and setInterval(), the Alarms API is designed specifically for background pages that may be loaded on demand, making it essential for extensions that need reliable scheduling regardless of when the extension's background context is active.

Unlike the deprecated W3C Web Alarms specification which was intended for broader web application use but never achieved widespread browser implementation, the extension-based Alarms API has become the de facto standard for scheduled tasks in the browser extension ecosystem.

For modern web development projects requiring browser extensions, the Alarms API bridges the gap between scheduling requirements and the event-driven architecture of browser extensions.

Key Characteristics

  • No persistence across browser sessions: Alarms are cleared when the browser restarts
  • Global scope: Alarms created in one extension context are visible to all other contexts
  • Not available in content scripts: Alarm scheduling must be handled by the background service worker or popup
  • Reliable scheduling: Works with Chrome's native scheduling system rather than JavaScript timers
Why Use the Alarms API?

Key advantages over standard JavaScript timers

Works with Background Service Workers

Unlike setTimeout/setInterval, Alarms API works reliably with Chrome's extension architecture including Manifest V3 service workers.

Survives Context Unloading

Alarms persist even when the background service worker is terminated, firing when the scheduled time arrives.

Integrated with Extension Lifecycle

Purpose-built for extensions with proper integration into Chrome's extension system and event handling.

Precise Scheduling Control

Support for one-time alarms, repeating alarms, and specific timestamp-based scheduling for flexible task management.

Core Methods

The create() Method

The chrome.alarms.create() method is the primary entry point for scheduling tasks. It accepts two parameters: an optional name string to identify the alarm, and an AlarmCreateInfo object that specifies when and how the alarm should fire.

The most basic alarm configuration uses the delayInMinutes property to schedule a one-time alarm that fires after a specified number of minutes. This approach works well for deferred tasks that need to execute once after a delay. For recurring alarms, the periodInMinutes property creates an alarm that fires repeatedly at the specified interval, with the first firing occurring after delayInMinutes if provided, otherwise immediately. For more precise scheduling, the when property accepts a Unix timestamp in milliseconds representing the exact time when the alarm should fire, enabling scheduling for specific times of day which proves particularly useful for notification systems or daily tasks.

The get() and getAll() Methods

Retrieving information about existing alarms enables extensions to check their scheduling state and make informed decisions about alarm management. The chrome.alarms.get() method retrieves a specific alarm by name, returning an Alarm object with details about its scheduled firing time and configuration. The chrome.alarms.getAll() method retrieves all currently scheduled alarms, providing a complete picture of the extension's scheduled tasks. The Alarm object returned contains two key properties: name (the alarm's identifier string) and scheduledTime (a Unix timestamp in milliseconds indicating when the alarm will fire). For recurring alarms, the periodInMinutes property is also present, though it may be absent for one-time alarms created with when instead of periodInMinutes.

The clear() and clearAll() Methods

Managing alarm lifecycle includes the ability to cancel alarms when they're no longer needed. The chrome.alarms.clear() method removes a specific alarm by name, while chrome.alarms.clearAll() removes all scheduled alarms for the extension. Both methods accept an optional callback parameter that receives a boolean indicating whether any alarms were actually cleared. This return value helps extensions determine if cleanup was successful and whether additional cleanup steps might be necessary. Proper alarm cleanup is important for extension hygiene since unnecessary alarms consume system resources and can create confusion when debugging or when extensions need to update their scheduling behavior.

Creating and Managing Alarms
1javascript2// Schedule an alarm to fire in 30 minutes3chrome.alarms.create('delayed-task', {4 delayInMinutes: 305});6 7// Create a recurring alarm that fires every hour8chrome.alarms.create('hourly-sync', {9 periodInMinutes: 6010});11 12// Schedule an alarm for a specific date and time13const targetTime = new Date('2025-01-15T09:00:00Z').getTime();14chrome.alarms.create('morning-task', { when: targetTime });15 16// Retrieve alarm information17chrome.alarms.get('hourly-sync', (alarm) => {18 if (alarm) {19 console.log(`Next alarm: ${new Date(alarm.scheduledTime)}`);20 }21});22 23// Clear a specific alarm24chrome.alarms.clear('deprecated-task', (wasCleared) => {25 if (wasCleared) console.log('Alarm cleared');26});

Responding to Alarm Events

The onAlarm Event Listener

The chrome.alarms.onAlarm event fires whenever any of an extension's alarms reach their scheduled time. Setting up a listener for this event is essential for actually executing the code you want to schedule. The alarm object passed to the listener contains a name property that identifies which alarm triggered the event, enabling a single listener to manage multiple scheduled tasks efficiently. For extensions with many alarms, organizing the listener logic using a switch statement or lookup object to dispatch based on alarm name provides maintainable code that handles alarm routing cleanly.

Implementing Recurring Task Logic

Recurring alarms require additional consideration to ensure reliable operation over extended periods. Because alarms don't persist across browser restarts, recurring tasks must reconstruct their schedule when the extension initializes. For tasks that require more precise timing than periodic alarms provide, such as daily tasks that must run at specific times, implementing the scheduling logic within the alarm handler ensures accuracy by rescheduling for the next occurrence after each execution. This approach ensures that daily tasks execute at the intended time regardless of when the extension was installed or when the browser last restarted.

Practical Code Examples

Periodic Content Refresh

Extensions that display cached content often need to refresh that content in the background. This pattern combines the Alarms API with Chrome's storage and messaging APIs to create a robust content synchronization system. The implementation creates an alarm for periodic refresh, listens for the alarm event to trigger the fetch operation, updates the cache using Chrome's storage API, and notifies any open extension pages about the update through the messaging API. Error handling includes a retry mechanism that schedules a separate alarm for retry attempts when content refresh fails.

Notification Scheduler

Many extensions need to notify users at specific times, such as reminders or deadline alerts. The Alarms API handles the scheduling while other APIs manage the actual notification delivery. This implementation separates scheduling concerns from notification delivery, making each part easier to test and maintain. When scheduling a notification, the notification data is stored separately so it can be retrieved when the alarm fires, even if the original scheduling code has been garbage collected. The notification alarm handler retrieves the stored data and uses the chrome.notifications API to display the actual notification to the user.

Data Cleanup Routine

Background cleanup tasks prevent extensions from accumulating unnecessary data over time. Regular cleanup maintains performance and reduces storage usage. This cleanup routine demonstrates several best practices: it runs at a consistent time rather than relying on intervals that might drift, it handles multiple storage areas by cleaning both cached items and notification history, and it logs its activities for debugging purposes. The routine removes items older than a configurable threshold while preserving recent data, helping extensions maintain optimal performance over extended periods of use.

Best Practices and Performance

Optimizing Alarm Precision

The Alarms API provides reasonable precision for most extension use cases, but understanding its behavior helps when more precise timing matters. Alarms may fire slightly later than scheduled, particularly during periods of system inactivity when browsers optimize power consumption. When precise timing is required, consider using the alarm's when property with a small buffer rather than delayInMinutes or periodInMinutes. The when property provides more control over the exact firing time. For recurring tasks that must maintain consistent timing despite potential delays, implementing a drift-correction mechanism in the alarm handler can help maintain accuracy over time.

Managing Resource Usage

While alarms are lightweight compared to continuously running background processes, extensions should be mindful of resource usage. Creating excessive alarms or alarms with very short periods can impact system performance and battery life on mobile devices. Recommended practices include consolidating related tasks into single alarms rather than creating separate alarms for each task, using longer periods for non-urgent tasks such as hourly or daily rather than per-minute, and implementing logic to pause or reduce alarm frequency when the device is in battery-saver mode. Extensions can check system conditions before performing resource-intensive operations triggered by alarms.

Error Handling and Resilience

Robust alarm handling includes proper error management to prevent failed alarms from blocking future executions. JavaScript errors in alarm listeners don't prevent future alarm firings, but they can cause data loss or inconsistent state. Using try-catch blocks in alarm listeners, implementing remote error tracking for production monitoring, creating retry mechanisms for transient failures, and properly cleaning up after errors all contribute to resilient alarm handling that maintains extension reliability.

Security Considerations

When scheduling alarms that perform network requests or access sensitive data, security considerations apply. Always validate any data received from external sources before processing, use HTTPS for network requests triggered by alarms, and limit the permissions requested to only what's necessary for the alarm's functionality. Extensions should also consider user privacy when scheduling background activity, providing transparent communication about background operations and user controls over alarm frequency to build trust and meet privacy expectations.

Browser Compatibility

The Alarms API is available in Chrome, Edge, Firefox, and other Chromium-based browsers through their extension platforms. Chrome provides the most comprehensive Alarms API implementation and serves as the reference implementation for the API. Firefox supports the core functionality with minor differences in how alarms interact with the browser's privacy protections, particularly around background activity restrictions. Safari's WebExtensions implementation includes alarms support but with some limitations around background page persistence and more restrictive background activity policies.

When building extensions for multiple browsers, testing alarm behavior across target browsers is essential. The MDN browser compatibility table provides detailed information about specific method support and behavioral differences. Pay particular attention to how each browser handles alarm persistence across sessions, timing precision under various conditions, and interactions with browser-specific privacy features that may affect alarm behavior.

For cross-browser extension development, consider how background task scheduling fits into your overall AI automation strategy, ensuring consistent behavior across different browser implementations.

Frequently Asked Questions

Do alarms persist when the browser restarts?

No, alarms do not persist across browser sessions. Extensions must recreate their recurring alarms when they initialize or when the background page loads.

Can content scripts use the Alarms API?

No, the Alarms API is not available in content scripts. Alarm scheduling must be handled by the extension's background script or other privileged context.

What's the minimum alarm interval?

While the API accepts any positive number, alarms with very short intervals (less than a minute) may experience precision issues. Consider the intended use case when choosing intervals.

How many alarms can an extension create?

Chrome allows extensions to create multiple alarms, though performance may degrade with extremely large numbers. Consolidating related tasks into fewer alarms is recommended.

Can alarms fire while the browser is closed?

Alarms cannot fire while the browser is fully closed. When the browser restarts and the extension loads, any scheduled alarms will fire at their next scheduled time.

How does the Alarms API differ from setInterval?

Unlike setInterval, the Alarms API works with background pages that are loaded on demand. Alarms survive extension context unloading and integrate with the browser's native scheduling system.

Summary

The Alarms API provides browser extensions with a reliable mechanism for scheduling code execution at specific times or regular intervals. Key takeaways include:

  • Core methods: create(), get(), getAll(), clear(), clearAll() provide complete alarm lifecycle management
  • Event handling: onAlarm listener enables response to scheduled firing times
  • Recurring tasks: Require recreation on extension startup and careful scheduling logic
  • Performance: Choose appropriate intervals and consolidate related tasks
  • Cross-browser: Support varies; test across target browsers

For modern web development, the Alarms API represents an essential tool for building extensions with background scheduling capabilities. When combined with SEO best practices, browser extensions can provide powerful tools for automated monitoring, content updates, and data analysis that enhance overall digital marketing efforts.

Build powerful browser extensions with Digital Thrive

Our team specializes in creating feature-rich browser extensions with reliable background task scheduling and seamless user experiences.