今回は、HTML、JavaScriptを使って、Webタイマーを作成していきたいと思います!
プログラミング初心者でもできる内容になっているかと思います!
解説を見つつタイマーを作成してみましょう!
目次
各ファイルの作成
まずは必要となるファイルを用意しましょう。
今回必要となるファイルは、
- index.html
- style.css
- timer.js
以上の3点になります。
すべて同じディレクトリ内に配置しましょう。
ディレクトリ構造は以下のようになります。
web-timer
├── index.html
├── style.css
└── timer.js
上記の構造ですが、ターミナルを使用してコマンドで作成することが可能です。
以下のコマンドを、1つずつターミナルに入力しましょう。
# フォルダの作成
mkdir web-timer
# 作成したフォルダに移動
cd web-timer
# 各ファイルの作成
touch index.html style.css timer.js
# web-timer内に各ファイルが作成できているか確認
ls
これで準備はできました!
次にview(index.html、style.css)を記述していきます。
viewの作成
ファイルの配置ができたので、viewの作成をしていきたいと思います。
まずは、index.htmlです。
見本と同じ見た目でよければ、下記のコードをコピペして使用していただいて構いません。
headタグの中に、CSSとJavaScriptファイルを読み込むための記述があるので、こちらは抜けがないようにしておきましょう。
index.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta http-equiv="X-UA-Compatible" content="IE=edge" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>WebTimer</title>
<link rel="stylesheet" type="text/css" href="http://yui.yahooapis.com/3.18.1/build/cssreset/cssreset-min.css"/>
<link rel="stylesheet" href="style.css" />
<script src="timer.js"></script>
</head>
<body>
<h3 class="free-time">Web_Timer</h3>
<div class="time-view">
<div class="free-block">
<input type="text" placeholder="00" class="free-timer" autofocus="true" id="free-min"/>
<span class="free">:</span>
<input type="text" placeholder="00" class="free-timer" id="free-sec" />
</div>
<div class="min-sec">
<button value="10" id="min-10" class="add-btn">10分</button>
<button value="5" id="min-5" class="add-btn">5分</button>
<button value="1" id="min-1" class="add-btn">1分</button>
</div>
<div class="free-box">
<input type="button" value="start" id="free-start" />
<input type="button" value="stop" disabled="" id="free-stop" />
<input type="button" value="reset" disabled="" id="free-reset" />
</div>
</div>
</body>
</html>
次にCSSになります。
style.css
* {
box-sizing: border-box;
}
.free-time{
text-align: center;
margin-top: 30px;
font-size: 50px;
font-weight: bold;
}
.free-block{
display: flex;
align-items: center;
justify-content: center;
margin: 0 auto;
height: 100px;
line-height: 100px;
width: 30vw;
border: 3px solid black;
padding: 10px;
}
.free-timer{
height: 60px;
line-height: 60px;
display: block;
text-align: center;
font-size: 60px;
width: 40%;
border-style: none;
background-color: white;
color: black;
}
.free{
font-weight: bold;
font-size: 30px;
margin: 0 10px;
}
.free-box{
margin-top: 10px;
display: flex;
align-items: center;
justify-content: center;
}
.min-sec{
display: flex;
justify-content: center;
}
.add-btn{
margin: 5px 5px 0 0;
font-size: 20px;
color: black;
background-color: #DCC2FF;
border-bottom: 5px solid #9057FF;
}
#free-start{
display: block;
font-size: 30px;
color: #fff;
background-color: #eb6100;
border-bottom: 5px solid #b84c00;
}
#free-stop{
display: block;
margin: 0 10px;
font-size: 30px;
color: #b84c00;
background-color: #eb6100;
border-bottom: 5px solid #b84c00;
}
#free-reset{
display: block;
font-size: 30px;
color: #b84c00;
background-color: #eb6100;
border-bottom: 5px solid #b84c00;
}
#count-memo{
font-size: 20px;
font-weight: bold;
color: red;
padding: 0 5px;
}
.free-time{
margin: 0 auto;
}
これで見本と同じ見た目のviewが出来上がったかと思います。
一度、index.htmlをブラウザで表示してみましょう。
ファイルをブラウザにドラッグ&ドロップすることで確認することが可能です。
このあとは、タイマーの機能を実装していきます。
タイマー機能の実装 ~jsファイルの読み込み確認~
今回タイマー機能を実装するにあたって、以下の項目を必須項目にしていきたいと思います。
- 時間を設定してstartボタンを押すと、カウントダウンが始まる
- カウントダウン中にstopボタンを押すと、カウントダウンが止まる
- stopしたあと、resetボタンを押すと設定していた時間がリセットされる
- カウントダウン終了後に、alertで「時間です!」と表示される
任意で以下の項目も実装してみてもいいかと思います。
- カウントダウン中は、時間の設定(入力)ができない
- カウントダウン中は、start、resetボタンが押せない
- 10分、5分、1分のボタンを押したら時間を設定することができる
ここからは、JavaScriptを使って実際にタイマーの機能を実装していきます。
編集するファイルは、timer.jsになります。
まずは、timer.jsが読み込めているか確認をしていきます。
window.addEventListener("DOMContentLoaded", () => {
alert("正常に読み込めています");
});
ブラウザをリロードしたときに、このような表示が出てきたらOKです!
alert("正常に読み込めています");
こちらの記述は不要になりますので削除しておきましょう。
timer.jsが読み込みが確認できたら次に進みましょう。
タイマー機能の実装 ~startボタン、カウントダウン~
こちらでは、startボタンを押したら、カウントダウンの処理を実装していきます。
手順としては、以下のようになります。
- 時間設定の要素(input要素)、startボタンの要素を取得
- startボタンがクリックされたら、イベントを発火させる
- 設定された時間(値)を取得し、時間の単位を秒に設定する
- 時間(値)が0になるまで、カウントダウンの処理を実施
まずは、手順1を行っていきます。
timer.jsを以下のように記述しましょう。
window.addEventListener("DOMContentLoaded", () => {
const inputMin = document.getElementById("free-min");
const inputSec = document.getElementById("free-sec");
const freeStart = document.getElementById("free-start")
console.log(inputMin);
console.log(inputSec);
console.log(freeStart);
});
記述ができたら、ブラウザをリロードして検証ツールを開きましょう。
画像のようにcondoleに取得した要素(input要素)が表示されていたらOKです。
取得できていることが確認できたら、
console.log(inputMin);
console.log(inputSec);
console.log(freeStart);
こちらの記述を削除しておきましょう。
次に、手順2に進みます。
timer.jsの記述を以下のようにしましょう。
window.addEventListener("DOMContentLoaded", () => {
const inputMin = document.getElementById("free-min");
const inputSec = document.getElementById("free-sec");
const freeStart = document.getElementById("free-start")
freeStart.addEventListener("click", () => {
alert("イベント発火");
});
});
ブラウザをリロードしてから、stratボタンをクリックしてみましょう。
以下の画像のようにalertが表示されたらOKです!
イベントの発火が確認ができたら、alert("イベント発火");
は削除しておきましょう。
次に、手順3を実装していきます。
timer.jsを以下のように記述しましょう。
window.addEventListener("DOMContentLoaded", () => {
const inputMin = document.getElementById("free-min");
const inputSec = document.getElementById("free-sec");
const freeStart = document.getElementById("free-start")
freeStart.addEventListener("click", () => {
let countMin = parseInt(inputMin.value * 60); //時間(分)を秒に変換する処理
let countSec = parseInt(inputSec.value);
let mixValue = countMin + countSec;
console.log(mixValue);
});
});
記述ができたら、ブラウザをリロードして検証ツールを開きましょう。
実際に時間を入力して、startボタンを押した際に検証ツールのconsoleに時間が秒数に置き換えられて表示されていたらOKです。
例)1:30と入力した場合は、90と表示される(画像参照)
値を取得することができたでしょうか?
確認ができたら、console.log(mixValue);
は削除しておきましょう。
少しずつ内容は難しくなりますが、理解できない内容ではないと思いますので頑張りましょう。
次に、手順4に進みます。
timer.jsを以下のように記述しましょう。
window.addEventListener("DOMContentLoaded", () => {
const inputMin = document.getElementById("free-min");
const inputSec = document.getElementById("free-sec");
const freeStart = document.getElementById("free-start")
freeStart.addEventListener("click", () => {
let countMin = inputMin.value * 60;
let countSec = inputSec.value;
if (countMin == "") {
// 分の入力がなかった場合に計算できなくなってしまうため、0を代入する
countMin = 0;
}
if (countSec == "") {
// 秒数の入力がなかった場合に計算できなくなってしまうため、0を代入する
countSec = 0;
}
let mixValue = parseInt(countMin) + parseInt(countSec);
// カウントダウン処理定義
const freeCount = () => {
mixValue -= 1
freeMin = Math.floor(mixValue / 60);
freeSec = Math.floor(mixValue % 60);
// 10分以下の表示
if (freeMin < 10 ) {
inputMin.value = `0${freeMin}`
} else {
inputMin.value = freeMin
}
// 10秒以下の表示
if (freeSec < 10 ) {
inputSec.value = `0${freeSec}`
} else {
inputSec.value = freeSec
}
if (mixValue < 0) {
alert("時間です!")
inputMin.value = ""
inputSec.value = ""
clearInterval(freeInterval);
}
}
// カウントダウン処理の実行
freeCount(mixValue);
// 1秒ずつ処理を進める
const freeInterval = setInterval(freeCount, 1000);
});
});
記述することができたら、ブラウザをリロードしてから時間を設定、startボタンを押してみましょう。
以下の動画のようにカウントダウンができていたらOKです。
確認できたでしょうか?
今回記述した内容は、ざっくり以下のようになります。
- 入力された時間を取得して、合計値の計算をする
- カウントダウンの処理を関数式として定義
- カウントダウンの処理を呼び出す、引数に1で計算した値を持たせる
- setIntervalを使用し、1秒ごとに処理を進める
- 1で計算した値が0になったら処理を止める
タイマー機能の実装 ~stop機能実装~
こちらでは、stopボタンを押したときの処理を実装していきたいと思います。
手順は、以下のようになります。
- stopボタンの要素を取得、クリックしたときにイベント発火
- 1秒ごとに行われている処理を止める
まずは、手順1を行っていきます。
timer.jsを以下のように記述しましょう。
window.addEventListener("DOMContentLoaded", () => {
const inputMin = document.getElementById("free-min");
const inputSec = document.getElementById("free-sec");
const freeStart = document.getElementById("free-start")
// ①stopボタンの要素を取得
const freeStop = document.getElementById("free-stop")
freeStart.addEventListener("click", () => {
// ②stopボタンを押せるようにする & 色の切り替え
freeStop.disabled = false;
freeStop.setAttribute("style", "color: #fff;")
let countMin = inputMin.value * 60;
let countSec = inputSec.value;
if (countMin == "") {
countMin = 0;
}
if (countSec == "") {
countSec = 0;
}
let mixValue = parseInt(countMin) + parseInt(countSec);
const freeCount = () => {
// ③stopボタンを押したときの処理
freeStop.addEventListener("click", () => {
console.log("stop機能");
})
mixValue -= 1
freeMin = Math.floor(mixValue / 60);
freeSec = Math.floor(mixValue % 60);
if (freeMin < 10 ) {
inputMin.value = `0${freeMin}`
} else {
inputMin.value = freeMin
}
if (freeSec < 10 ) {
inputSec.value = `0${freeSec}`
} else {
inputSec.value = freeSec
}
if (mixValue < 0) {
alert("時間です!")
inputMin.value = ""
inputSec.value = ""
clearInterval(freeInterval);
}
}
freeCount(mixValue);
const freeInterval = setInterval(freeCount, 1000);
});
});
今回記述した内容は、以下のとおりです。
- ①では、stopボタンの要素を取得
- ②では、startボタンを押したときにstopボタンにかかっている
disabled
を外し、わかりやすく色を変更 - ③では、①で取得したstopボタンがクリックされたときのイベント発火を確認
実際にイベントが発火しているか確認してみましょう。
- 時間を設定
- startボタンを押してカウントダウンが始まってから、stopボタンを押す
- 検証ツールのconsoleに「stop機能」が表示されていればOK
以下の動画のようになっていれば問題ありません。
確認が取れたら、console.log("stop機能");
は削除しておきましょう。
次に、手順2を実装していきます。
timer.jsを以下のように記述しましょう。
window.addEventListener("DOMContentLoaded", () => {
const inputMin = document.getElementById("free-min");
const inputSec = document.getElementById("free-sec");
const freeStart = document.getElementById("free-start")
const freeStop = document.getElementById("free-stop")
freeStart.addEventListener("click", () => {
freeStop.disabled = false;
freeStop.setAttribute("style", "color: #fff;")
let countMin = inputMin.value * 60;
let countSec = inputSec.value;
if (countMin == "") {
countMin = 0;
}
if (countSec == "") {
countSec = 0;
}
let mixValue = parseInt(countMin) + parseInt(countSec);
const freeCount = () => {
freeStop.addEventListener("click", () => {
// 処理を止めるための記述
clearInterval(freeInterval);
})
mixValue -= 1
freeMin = Math.floor(mixValue / 60);
freeSec = Math.floor(mixValue % 60);
if (freeMin < 10 ) {
inputMin.value = `0${freeMin}`
} else {
inputMin.value = freeMin
}
if (freeSec < 10 ) {
inputSec.value = `0${freeSec}`
} else {
inputSec.value = freeSec
}
if (mixValue < 0) {
alert("時間です!")
inputMin.value = ""
inputSec.value = ""
clearInterval(freeInterval);
}
}
freeCount(mixValue);
const freeInterval = setInterval(freeCount, 1000);
});
});
今回記述したのは、1行だけです。
setInterval
で動いている処理をclearInterval(freeInterval);
で止めます。
問題なく止まるか確認してみましょう。
以下の動画のようになっていればOKです。
確認することができたでしょうか?
stop機能は以上となります。
では、最後にreset機能の実装をしていきましょう。
タイマー機能の実装 ~reset機能実装~
最後にreset機能を実装していきます。
手順は、以下のようになります。
- resetボタンの要素を取得、resetボタンを押せるようにする
- resetボタンをクリックしたらイベント発火、設定されている時間をリセットする処理を記述
まずは、手順1を実装していきます。
timer.jsを以下のように記述しましょう。
window.addEventListener("DOMContentLoaded", () => {
const inputMin = document.getElementById("free-min");
const inputSec = document.getElementById("free-sec");
const freeStart = document.getElementById("free-start");
const freeStop = document.getElementById("free-stop");
// リセットボタンの要素を取得 & リセットボタンを押せるようにする & 色の切り替え
const freeReset = document.getElementById("free-reset");
freeReset.disabled = false;
freeReset.setAttribute("style", "color: #fff;");
freeStart.addEventListener("click", () => {
freeStop.disabled = false;
freeStop.setAttribute("style", "color: #fff;");
let countMin = inputMin.value * 60;
let countSec = inputSec.value;
if (countMin == "") {
countMin = 0;
}
if (countSec == "") {
countSec = 0;
}
let mixValue = parseInt(countMin) + parseInt(countSec);
const freeCount = () => {
freeStop.addEventListener("click", () => {
clearInterval(freeInterval);
})
mixValue -= 1
freeMin = Math.floor(mixValue / 60);
freeSec = Math.floor(mixValue % 60);
if (freeMin < 10 ) {
inputMin.value = `0${freeMin}`
} else {
inputMin.value = freeMin
}
if (freeSec < 10 ) {
inputSec.value = `0${freeSec}`
} else {
inputSec.value = freeSec
}
if (mixValue < 0) {
alert("時間です!")
inputMin.value = ""
inputSec.value = ""
clearInterval(freeInterval);
}
}
freeCount(mixValue);
const freeInterval = setInterval(freeCount, 1000);
});
});
記述ができたら確認していきます。
今回はconsole.logを使用していませんが、resetボタンの要素を取得できているか確認したい場合は、各自で確認してみましょう。
ブラウザをリロードしてresetボタンが押せるようになっているか確認してみましょう。
現時点では、押しても何も起きません。
確認することができたら次に進みましょう。
いよいよ最後です。
手順2を実装していきます。
timer.jsを以下のように記述しましょう。
window.addEventListener("DOMContentLoaded", () => {
const inputMin = document.getElementById("free-min");
const inputSec = document.getElementById("free-sec");
const freeStart = document.getElementById("free-start");
const freeStop = document.getElementById("free-stop");
const freeReset = document.getElementById("free-reset");
freeReset.disabled = false;
freeReset.setAttribute("style", "color: #fff;");
freeStart.addEventListener("click", () => {
freeStop.disabled = false;
freeStop.setAttribute("style", "color: #fff;");
let countMin = inputMin.value * 60;
let countSec = inputSec.value;
if (countMin == "") {
countMin = 0;
}
if (countSec == "") {
countSec = 0;
}
let mixValue = parseInt(countMin) + parseInt(countSec);
const freeCount = () => {
freeStop.addEventListener("click", () => {
clearInterval(freeInterval);
})
mixValue -= 1
freeMin = Math.floor(mixValue / 60);
freeSec = Math.floor(mixValue % 60);
if (freeMin < 10 ) {
inputMin.value = `0${freeMin}`
} else {
inputMin.value = freeMin
}
if (freeSec < 10 ) {
inputSec.value = `0${freeSec}`
} else {
inputSec.value = freeSec
}
if (mixValue < 0) {
alert("時間です!")
inputMin.value = ""
inputSec.value = ""
clearInterval(freeInterval);
}
}
freeCount(mixValue);
const freeInterval = setInterval(freeCount, 1000);
});
// resetボタンを押した際の処理
freeReset.addEventListener("click", () => {
inputMin.value = "";
inputSec.value = "";
});
});
記述ができたら確認していきましょう。
処理の内容としては、クリックしたら時間の入力欄を空にしています。
以下の動画のように挙動が確認できたら完成です。
確認できたでしょうか?
以上で、reset機能の実装は終了です!
最後に
今回実装した内容は以下になります。
- 時間を設定してstartボタンを押すと、カウントダウンが始まる
- カウントダウン中にstopボタンを押すと、カウントダウンが止まる
- stopしたあと、resetボタンを押すと設定していた時間がリセットされる
- カウントダウン終了後に、alertで「時間です!」と表示される
興味のある方は、以下の任意項目の実装にもチャレンジしてみてください!
- カウントダウン中は、時間の設定(入力)ができない
- カウントダウン中は、start、resetボタンが押せない
- 10分、5分、1分のボタンを押したら時間を設定することができる
最後までご覧頂きありがとうございました。
この機会をきっかけにプログラミングに興味を持っていただけたら嬉しいです。