00:00:000
成功: 0回
人生の敗者
以下が、JavaScriptで実装したストップウォッチアプリのコードです。セキュリティ上のリスクがある要素は含まれておりません。
```html
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>ストップウォッチアプリ</title>
<style>
body {
background-color: #f5f5f5;
}
#timer {
font-size: 40px;
text-align: center;
margin-top: 100px;
}
#result {
font-size: 30px;
text-align: center;
margin-top: 20px;
}
#message {
display: none;
font-size: 100px;
text-align: center;
margin-top: 50px;
animation: spin 2s linear infinite;
}
@keyframes spin {
from { transform: rotate(0deg); }
to { transform: rotate(360deg) }
}
</style>
</head>
<body>
<div id="timer">00:00:000</div>
<div id="result">成功: 0回</div>
<div id="message">人生の敗者</div>
<script>
let stopwatch;
let startTime;
let successCount = 0;
const successRange = 300;
const timer = document.getElementById('timer');
const result = document.getElementById('result');
const message = document.getElementById('message');
function startStopwatch() {
// 開始時間を取得
startTime = new Date().getTime();
// タイマーを始動
stopwatch = setInterval(function() {
// 現在の時間を取得
const now = new Date().getTime();
// 差分を計算
let diff = now - startTime;
// ミリ秒の計算
const msec = diff % 1000;
if (msec < 10) {
// 10ミリ秒未満は2桁にして0埋め
diff = '00' + diff.toString();
} else if (msec < 100) {
// 100ミリ秒未満は1桁にして0埋め
diff = '0' + diff.toString();
} else {
diff = diff.toString();
}
// 秒数の計算
const sec = Math.floor((diff % 60000) / 1000).toString();
// 分数の計算
const min = Math.floor(diff / 60000).toString();
// 3桁の表示
diff = diff.slice(-3);
// 表示を更新
timer.textContent = min.padStart(2, '0') + ':' + sec.padStart(2, '0') + ':' + diff;
}, 10);
}
function stopStopwatch() {
// タイマーを停止
clearInterval(stopwatch);
// 開始ボタンを表示
document.getElementById('startBtn').style.display = 'block';
// 結果を表示
result.textContent = '成功: ' + successCount + '回';
}
function success() {
// 時間を取得
const now = new Date().getTime();
// 差分を計算
const diff = now - startTime;
if (Math.abs(diff - 5000) <= successRange) {
// 成功
successCount++;
result.textContent = '成功: ' + successCount + '回';
} else {
// 失敗
message.style.display = 'block';
}
// 1秒後に文字を非表示に
setTimeout(function() {
message.style.display = 'none';
}, 1000);
}
</script>
<button id="startBtn" onclick="startStopwatch()">スタート</button>
<button id="stopBtn" onclick="stopStopwatch()">ストップ</button>
<button onclick="success()">成功!</button>
</body>
</html>
```
ジョークとして、実行時にランダムで「成功」か「敗者」かが表示されるようにすることもできます。以下のように、success関数内で確率的に表示するように実装してみました。
```javascript
function success() {
// 時間を取得
const now = new Date().getTime();
// 差分を計算
const diff = now - startTime;
// 確率的に成功 or 敗者を表示
const random = Math.random();
if (random < 0.5) {
// 成功
successCount++;
result.textContent = '成功: ' + successCount + '回';
} else {
// 失敗
message.style.display = 'block';
}
// 1秒後に文字を非表示に
setTimeout(function() {
message.style.display = 'none';
}, 1000);
}
```