LoginSignup
0
1

More than 3 years have passed since last update.

javascriptでインターバルタイマーを作ってみた。

Last updated at Posted at 2020-06-03

javascriptでインターバルタイマーを作ってみた。

仕様
・1秒ごとに音がなる。
・フォームに秒数を入れると、入力された秒数毎に別の音がなる。

<!DOCTYPE html>
<html lang="ja">
<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>インターバルタイマー</title>
  <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css" integrity="sha384-ggOyR0iXCbMQv3Xipma34MD+dH/1fQ784/j6cY/iJTQUOhcWr7x9JvoRxT2MZw1T" crossorigin="anonymous">
<style>
   h1{
      font-size:24px;
   }
#PassageArea{
   font-size:42px;
   border:1px solid #666;
   padding:20px;
   width:100px;
   margin:0px auto;
}
</style>

</head>
<body>

<div class="container mt-5" style="text-align:center;">

   <h1>インターバルタイマー</h1>

   <div class="container mt-5">
      <div id="PassageArea">0</div>
   </div>

   <div class="container mt-5">
      <input type="number" id="number" min=1 value=5 style="width:80px;">
   </div>

   <div class="container mt-5">
      <button class="btn btn-primary" id="startcount" onclick="startShowing();">カウント開始</button>
      <button class="btn btn-primary" id="endcount" onclick="stopShowing();">カウント停止</button>
   </div>
</div>

<script>
var msg;
var number;
var count = 0;
var timer_id;

function startShowing() {
   count = 0;
   number = document.getElementById("number").value;
   document.getElementById("startcount").disabled = true;
   countup();
}

function stopShowing() {
   count = 0;
   clearTimeout(timer_id);
   document.getElementById("startcount").disabled = false;
}

function countup() {
   count ++;
   document.getElementById("PassageArea").innerHTML = count;
   console.log(count % number);
   if(count % number == 0){
      sound1();
   }else{
      sound2();
   }
   timer_id = setTimeout(countup,1000);
}

function sound1(){
    var id = 'sound-file1';
    if( typeof( document.getElementById( id ).currentTime ) != 'undefined' ){
        document.getElementById( id ).currentTime = 0;
    }
    document.getElementById( id ).play() ;
}

function sound2(){
    var id = 'sound-file2';
    if( typeof( document.getElementById( id ).currentTime ) != 'undefined' ){
        document.getElementById( id ).currentTime = 0;
    }
    document.getElementById( id ).play() ;
}
</script>

<audio id="sound-file1" preload="auto">
    <source src="beep1.mp3" type="audio/mp3">
</audio>

<audio id="sound-file2" preload="auto">
    <source src="beep2.mp3" type="audio/mp3">
</audio>

</body>
</html>
0
1
1

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
1