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:
1navigator.getBattery().then((battery) => {
2 console.log(`Battery level: ${Math.round(battery.level * 100)}%`)
3 // Battery level: 57%
4
5 console.log(`Battery discharging time: ${battery.dischargingTime / 60} minutes`)
6 // Battery discharging time: 179 minutes
7})
If you liked this tip, follow me on Twitter to get notified about new tips, blog posts, and more.
JavaScript Tip: How to Sort an Array of Integers
To sort an array of integers in JavaScript, we must provide a compare function that defines the sort order.
JavaScript Tip: Replace Switch Statements With Object Literals
I prefer using JavaScript's object literals over switch statements as the code is faster, more readable, and less verbose.