思ったより時間かかりました。
https://soundtimer.herokuapp.com/
index.html
<!DOCTYPE html>
<html lang="ja">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<link rel="stylesheet" href="css/styles.css">
<title>Sound Timer</title>
</head>
<body>
<audio id="music">
<source src="js/alarm.mp3" type="audio/mp3">
</audio>
<div id="timer">
00:00
</div>
<form name="minForm" id="minForm">
<input type="text" name="work_minutes" placeholder="minute">
<!-- <input type="text" name="break_minutes" placeholder="Break"> -->
</form>
<button id="start">start</button>
<!-- <button id="stop">stop</button>
<button id="reset">reset</button> -->
<script src="js/main.js"></script>
</body>
</html>
main.js
{
const displayTimer = document.getElementById('timer');
const minForm = document.getElementById('minForm');
const start = document.getElementById('start');
const stop = document.getElementById('stop');
const reset = document.getElementById('reset');
const music = document.getElementById('music');
let countdown;
let state = "work";
var audio = document.createElement('audio');
console.log(audio);
audio.id = 'sound';
audio.src = 'js/alarm.mp3';
function timer(seconds) {
let s = seconds;
const now = Date.now();
const then = now + seconds * 1000;
displayTimeLeft(seconds);
countdown = setInterval(() => {
const secondsLeft = Math.round((then - Date.now()) / 1000);
// check it we should stop it!
if(secondsLeft <= 0) {
clearInterval(countdown);
audio.play();
}
//display it
displayTimeLeft(secondsLeft);
}, 1000);
}
function displayTimeLeft(seconds) {
const m = Math.floor(seconds / 60);
const remainderSeconds = seconds % 60;
const display = `${String(m).padStart(2, '0')}:${String(remainderSeconds).padStart(2, '0')}`;
displayTimer.textContent = display;
}
start.addEventListener('click', () => {
const mins = minForm.work_minutes.value;
timer(mins * 60);
minForm.reset();
});
}