Navigation Menu

Skip to content

Instantly share code, notes, and snippets.

@JustinDFuller
Last active January 11, 2017 01:25
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save JustinDFuller/a35c05fd6dcebf8c8fe8f4f6335ba6c1 to your computer and use it in GitHub Desktop.
Save JustinDFuller/a35c05fd6dcebf8c8fe8f4f6335ba6c1 to your computer and use it in GitHub Desktop.
Watching for the battery getting low
let warningShowed = false;
if ('getBattery' in navigator) {
navigator.getBattery().then(battery => {
checkBatteryLevel();
battery.onchargingchange = checkBatteryLevel;
battery.onchargingtimechange = checkBatteryLevel;
battery.ondischargingtimechange = checkBatteryLevel;
battery.onlevelchange = checkBatteryLevel;
function checkBatteryLevel () {
// dischargingTime is seconds until battery is empty. 1200 is 20 minutes
// level is a percentage of 100. So 0.2 is 20%
if (battery.dischargingTime < 1200 || battery.level <= 0.2 && !warningShowed) {
alert(`Warning, battery level is at ${toPercentage(battery.level)}.`);
warningShowed = true;
}
}
});
}
/* Convert a decimal like 0.2 to a percentage: 20% */
function toPercentage(number) {
return `${Math.round(number * 100)}%`;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment