0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

音が鳴るタイマーをつくってみた

Last updated at Posted at 2019-08-16

思ったより時間かかりました。

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();
  });

}
0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?