Last active
January 11, 2017 01:25
-
-
Save JustinDFuller/a35c05fd6dcebf8c8fe8f4f6335ba6c1 to your computer and use it in GitHub Desktop.
Watching for the battery getting low
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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