See how to use the Wake Lock API to keep a screen or system awake until our application finishes a certain task.
In this age where wireless micro devices like PCs and smartphones are predominant, long battery life might be one of the most important features that any wireless device can have.
To achieve a long battery life, operating system (OS) manufacturers like Microsoft, Google and Apple have added various power-saving mechanisms to their OSes that limit the usage of computer resources when the device does not actively need it. They may turn on automatically when the device is idle or the battery is low or be turned on manually if you need to save battery or power.
A Wake Lock is a way to keep our screen or system awake when using any application that requires them to stay awake to finish its task and for satisfactory user experience.
In this guide, we will explore Wake Locks, their types and the Wake Lock API. We will build a simple application that will help us understand their automatic behavior, how to acquire them, how to release them and how to reacquire them when they are lost. By the end of this guide, we should be able to use the Wake Lock API to control when a user’s screen can dim, turn off or lock when they are using our web application.
To follow this guide, you need to be familiar with JavaScript.
As of January 2025, the Screen Wake Lock API is supported across all major browsers, including Chrome, Edge, Firefox and Safari.
As stated earlier, OS manufacturers have features built into their OSes to help wireless devices achieve longer battery life. Doing this involves limiting the usage of the screen and system (CPU) during idle times.
An OS may dim, lock or turn off the screen display during idle times or when the battery is low to extend the device’s battery life. For the processor (system), they may reduce CPU clock speed, throttle the processor and limit background processing.
When you think of “wake lock” as an English phrase about computers, you would imagine it would be some mechanism that keeps computers awake. If you think that, you are correct! Wake Locks are processes that prevent a device’s screen and/or computational abilities from going to sleep to optimize user experience in web applications.
Imagine yourself listening to a song and viewing its lyrics on Spotify, and one minute into the song, while you are reading the lyrics and singing along, your phone screen goes dark. In its attempt to save your battery, your phone turns off the screen because it has been one minute, and you haven’t interacted with the screen. How frustrating would that be? Now, you have to unlock your phone and go back ten seconds to the song to continue singing along.
Using a Wake Lock optimizes user experience by temporarily undoing what the OS manufacturers did to save power.
There are two types of wake locks:
Screen Wake Lock, when successfully acquired, prevents the OS from dimming, going off or locking the screen even when the device is idle or the battery is low.
System Wake Lock, when successfully acquired, prevents the OS from reducing CPU clock speed, throttling the processor or limiting background processing even when the device is idle or the battery is low.
In this guide, we will only discuss the Screen Wake Lock type because that is the only type of wake lock the Wake Lock API currently provides.
We use a Screen Wake Lock to prevent screen interruptions when running applications that require the screen to stay on for a good user experience.
Here are some examples of when we need to keep the screen awake:
In this post, we will be building a simple countdown timer. The timer will begin with the click of a button, followed by an acquisition of a Screen Wake Lock. We will release the Screen Wake Lock when the countdown timer is completed.
We will also illustrate instances where the Screen Locks may be automatically released. The goal is to show the use of Screen Wake Lock in an application without interaction with the device, but the screen staying on is crucial for a good user experience.
First, create a folder. You can name it whatever you want. I will name mine screen-wake-lock-demo
.
Open any text editor of your choice, i.e., Visual Studio Code. Find the folder you created from inside the text editor and open it. In the text editor, create a file named demo.html
and add the following to it:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>Screen Wake Lock Demo</title>
</head>
<body>
<h1>Demo - Countdown with Screen Wake Lock</h1>
</body>
</html>
Now, open the demo.html
file in any web browser of your choice, and you should see a page like the one below.
Let’s add a button
element to start the countdown and a paragraph to contain a text display of the countdown. Each tag has ID attributes that we will use to reference in the DOM.
We are also going to add a script that performs all of our desired tasks. You can create a different file for the script or write it inline as shown below.
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>Screen Wake Lock Demo</title>
</head>
<body>
<h1>Demo - Countdown with Screen Wake Lock</h1>
<button id="beginCountdown">Begin Countdown</button>
<p id="countdown">Countdown...</p>
<script>
let countdownDOM = document.getElementById("countdown");
let beginCountdownDOM = document.getElementById("beginCountdown");
let interval = null;
let wakeLock = null;
const beginCountdown = () => {};
beginCountdownDOM.addEventListener("click", beginCountdown);
</script>
</body>
</html>
In the code above, first we create variables that reference DOM elements. Then, we create the function beginCountdown
that starts the countdown and will be triggered by the click
event listener on the beginCountdown
button.
We disable the button when it is clicked to avoid overwriting an active countdown. Then, we set up a timer that runs every second using the setInterval
function. The callback runs down the 20-second countdown and only stops when the countdown gets to zero.
If you head over to your browser, you should see this:
The WakeLockSentinel
is an object returned when we successfully acquire a Wake Lock by calling the Wake Lock API. It is an interface to the acquired Wake Lock, providing us access to its status, properties and methods.
The WakeLockSentinel
holds three properties:
onrelease
: A method that triggers when the Wake Lock is automatically released.released
: A Boolean value that tells if the screen Wake Lock is active. False means it is active, while true means the wake lock is not active.type
: A string that tells us the kind of Screen Wake Lock applied, which can be either screen or system.If there is no instance of the WakeLockSentinel
, there can be no subsequent interaction with the acquired Wake Lock. This means there is no way to perform any further action on the Screen Wake Lock, such as releasing the Wake Lock; we have to allow the Wake Lock to be released automatically by taking the document out of view(closing tab).
Here’s how to initialize a reference for the WakeLockSentinel:
let wakeLock = null;
To acquire a Screen Wake Lock, we have to first request it. Requesting a Wake Lock is asking the operating system to apply the lock (by default, no lock is applied). The OS grants that request to acquire a Wake Lock only if the document is visible. A document not currently visible cannot acquire a Wake Lock.
It is important to note that the Screen Wake Lock API is only available when served over HTTPS. This is common among popular web APIs.
Now, let’s write a function that requests a Screen Wake Lock and successfully acquires it. We need to create an asynchronous function that requests for the Wake Lock because the Wake Lock API will return a promise.
let statusDOM = document.getElementById("status");
const requestWakeLock = async () => {
try {
wakeLock = await navigator.wakeLock.request("screen");
statusDOM.textContent = "Wake lock status: Active";
} catch (err) {
console.error(`Failed to request wake lock: ${err.name}, ${err.message}`);
}
};
Here, we call navigator.wakeLock.request
, which takes the desired Wake Lock type as the only parameter. This is optional because, as earlier stated, the Wake Lock API is limited to just screen
for now.
The navigator.wakeLock.request
returns a WakeLockSentinel
object that we will store in the wakeLock
reference we just created. If this fails, our catch
exception statement will output the error name and message in the console. If not, we will display that the Wake Lock was successfully acquired and applied.
Releasing a Screen Wake Lock, on the other hand, is telling the operating system to go back to its default state of not applying the Screen Wake Lock. Quite straightforward!
Now, let’s create a function that does that.
const releaseWakeLock = () => {
if (wakeLock) {
wakeLock.release();
wakeLock = null;
statusDOM.textContent = "Wake lock status: Released";
}
};
In the code above, we released the Screen Wake Lock by undoing everything we did to acquire it.
If you did all that correctly, you should have this:
As mentioned earlier, Screen Wake Locks have certain conditions that need to be met before they can be acquired and applied in a web application. One of those conditions is that the webpage that acquired the wake lock must be visible, meaning visibilityState
must be set to true
.
The Wake Lock automatically releases when visibilitystate
becomes false
, which happens when you minimize or switch away from a tab or window where a Screen Wake Lock is applied and active.
This automatic behavior may present two questions: How do we know when a Wake Lock automatically releases, and how can we reacquire it?
Well, here’s how:
wakeLock.addEventListener("release", async () => {
console.log("screen wake lock was released");
});
The event listener above listens for the onrelease
event of the WakeLockSentinel, and when the value is set to true
, that tells us the Wake Lock has been released.
document.addEventListener("visibilitychange", async () => {
if (document.visibilityState === "visible" && wakeLock !== null) {
console.log("document is visible, reacquiring wake lock");
await requestWakeLock();
}
});
This code block first listens for the visibilityChange
event, and the callback function checks for a visiblityState
state of the document, which, when set to true
, allows us to reacquire the lost Wake Lock.
Screen Wake Locks are applied in our everyday web apps, and they are so common that you are more likely to notice their absence than their presence in web applications when you expect uninterrupted screen time.
From Spotify to YouTube to video players on every website, having Screen Wake Locks applied to specific pages of web applications is expected from every website attempting to deliver a good user experience. This guide provides you with sufficient knowledge on Wake Locks and their types and the process of applying them to any web application to optimize the user’s experience.
Chris Nwamba is a Senior Developer Advocate at AWS focusing on AWS Amplify. He is also a teacher with years of experience building products and communities.