1 Minuten Lesezeit
JavaScript Tip: Get Valuable Info About Device Battery
TODO
KI-Assistent fragenMichael Hoffmann
@mokkapps

The Battery Status API provides information about the system's battery charge level and lets you be notified by events sent when the battery level or charging status changes.
Knowing a device's battery status can be helpful in several situations or use cases. Here are some examples:
- Save the application state before the battery runs out to prevent data loss.
- Pause heavy computations/animations when the battery is low.
- For example, an email client may check the server for new emails less frequently if the device is low on battery.
- Switch to dark mode when the battery is low, which can save energy.
Let's take a look at a simple example to get the device's battery status:
battery.js
navigator.getBattery().then((battery) => {
console.log(`Battery level: ${Math.round(battery.level * 100)}%`)
// Battery level: 57%
console.log(`Battery discharging time: ${battery.dischargingTime / 60} minutes`)
// Battery discharging time: 179 minutes
})