我創建了一個顯示交通信號燈的網站。當用戶點擊一個按鈕時,燈光依次變化。只是想知道,有沒有一種方法可以有一個「停止」按鈕,當用戶點擊它時,序列停止在它當前所在的圖像上?如何使我的停止按鈕取消我的交通燈序列?
這裏是我的代碼:
<!DOCTYPE html>
<html>
<body>
<h1><u> Traffic Light Sequence </u></h1>
<p>Press the button to begin.</p>
<img id="colour" src="F:\TrafficLightRed.jpg">
<button type="button" onclick="changeLights()">Change Lights</button>
<button type="button" onclick="resetLights()">Reset Lights</button>
<script>
var timeIndex = 0;
var lightIndex = 0;
var timer;
var trafficLight = document.getElementById('colour');
var lights = [{
duration: 2,
image: 'F:\TrafficLightRed.jpg'
}, {
duration: 2,
image: 'F:\TrafficLightRedAmber.jpg'
}, {
duration: 2,
image: 'F:\TrafficLightGreen.jpg'
}, {
duration: 2,
image: 'F:\TrafficLightAmber.jpg'
}]
function resetLights() {
lightIndex = 0
}
function changeLights() {
timeIndex++;
if(timeIndex == lights[lightIndex].duration) {
timeIndex = 0;
trafficLight.src = lights[lightIndex].image;
lightIndex = lightIndex + 1;
if(lightIndex == 4) {
lightIndex = 0
}
}
}
timer = setInterval(changeLights, 1000);
</script>
</body>
</html>
用[clearInterval()](https://developer.mozilla.org/en-US/docs/Web/API/WindowTimers/clearInterval) – charlietfl