<!DOCTYPE html>
<html>
<head>
<title>ランプアプリ</title>
<style type="text/css">
body {
margin: 0;
padding: 0;
text-align: center;
}
#lamps {
display: flex;
flex-direction: row;
align-items: center;
justify-content: center;
height: 200px;
}
#lamp1, #lamp2 {
background-color: gray;
height: 100px;
width: 100px;
border-radius: 50%;
margin: 20px;
}
.hidden {
display: none;
}
</style>
</head>
<body>
<h1>ランプアプリ</h1>
<div id="lamps">
<div id="lamp1"></div>
<div id="lamp2"></div>
</div>
<button id="startButton">スタートボタン</button>
<button id="stopButton" class="hidden">ストップボタン</button>
<script type="text/javascript">
let light1 = false;
let light2 = false;
const startButton = document.getElementById('startButton');
const stopButton = document.getElementById('stopButton');
const lamp1 = document.getElementById('lamp1');
const lamp2 = document.getElementById('lamp2');
const sleep = (ms) => {
return new Promise(resolve => setTimeout(resolve, ms));
}
const toggleLights = async () => {
while (true) {
light1 = !light1;
light2 = !light2;
if (light1) {
lamp1.style.backgroundColor = 'yellow';
} else {
lamp1.style.backgroundColor = 'gray';
}
if (light2) {
lamp2.style.backgroundColor = 'yellow';
} else {
lamp2.style.backgroundColor = 'gray';
}
await sleep(500);
}
}
const stopLights = async () => {
stopButton.disabled = true;
startButton.disabled = true;
let delay = 500;
for (let i = 0; i < 10; i++) {
await sleep(delay);
if (light1) {
lamp1.style.backgroundColor = 'gray';
light1 = false;
} else if (light2) {
lamp2.style.backgroundColor = 'gray';
light2 = false;
}
delay += 500;
}
const random = Math.floor(Math.random() * 2) + 1;
if (random === 1) {
lamp1.style.backgroundColor = 'yellow';
alert('左のランプが光っています。');
} else {
lamp2.style.backgroundColor = 'yellow';
alert('右のランプが光っています。');
}
stopButton.disabled = false;
startButton.disabled = false;
startButton.textContent = '再スタート';
stopButton.classList.add('hidden');
}
startButton.addEventListener('click', () => {
startButton.disabled = true;
toggleLights();
stopButton.classList.remove('hidden');
stopButton.disabled = false;
});
stopButton.addEventListener('click', () => {
stopLights();
});
</script>
</body>
</html>
(ジョーク:このランプアプリは、「明るい未来」を提供します。)