Skip to content

Instantly share code, notes, and snippets.

@brianloveswords
Created November 13, 2015 14:05
Show Gist options
  • Star 16 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save brianloveswords/20994820084a1968205d to your computer and use it in GitHub Desktop.
Save brianloveswords/20994820084a1968205d to your computer and use it in GitHub Desktop.
<audio id="alarm" src="alarm.ogg" controls></audio>
<script>
const alarmElement = document.getElementById('alarm');
const alarmTimes = [
new Date('2015-11-13 07:00 -0500'),
new Date('2015-11-13 08:00 -0500'),
new Date('2015-11-13 08:30 -0500'),
];
function playAlarm() {
alarmElement.currentTime = 0;
alarmElement.play();
}
function checkTime(time) {
if (Date.now() >= time) {
return playAlarm();
}
const diff = time - Date.now();
console.log('%s seconds until alarm', diff/1000|0);
setTimeout(playAlarm, diff);
}
function stopAlarm() {
alarmElement.pause();
}
alarmTimes.forEach(time => checkTime(time));
document.body.addEventListener('keypress', e => {
// Spacebar
if (e.keyCode == 32) {
stopAlarm()
}
});
</script>
@bsitruk
Copy link

bsitruk commented Nov 13, 2015

I learnt two little tricks :D

  1. double | 0 -> convert to integer
  2. date2 - date1 -> diff in ms

Thanks 👍

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment