嗨我正在尝试制作一套自动交通信号灯,但我无法让它们停止运行。我尝试过使用window.clearInterval()但它不会起作用。我这样做是为了我的GCSE控制评估。我真的不知道为什么这不会起作用所以任何帮助都会很棒。感谢。
var asset = [
"redyellow.png",
"green.png",
"yellow.png",
"red.png"
];
var counter = 0;
function changeLights() {
if (counter == asset.length) counter = 0;
var image = document.getElementById('redImg');
image.src=asset[counter];
counter = counter + 1;
}
var toggle = 1
function timer() {
if (toggle === 1) {
var on = setInterval(changeLights,5000)
}
else {
window.clearInterval()
}
}
function stopTimer() {
toggle = toggle + 1
}

<!DOCTYPE html>
<html>
<body>
<h1>Traffic Lights</h1>
<img id="redImg" src="red.png" alt="Red traffic light" />
<p>
<button type="button" onclick="timer()">Start Lights</button>
<button type="button" onclick="stopTimer()">Stop Lights</button>
</p>
</body>
</html>
&#13;
答案 0 :(得分:2)
尝试将间隔设为全局变量。您还需要致电self.clearInterval(interval)
。例如:
var interval;
function timer() {
interval = self.setInterval(changeLights, 5000);
}
function stopTimer() {
self.clearInterval(interval);
}
在你的情况下:
var asset = [
"redyellow.png",
"green.png",
"yellow.png",
"red.png"
];
var counter = 0;
var interval = null;
function changeLights() {
if (counter == asset.length) counter = 0;
var image = document.getElementById('redImg');
image.src = asset[counter];
image.alt = asset[counter]; // debug
counter = counter + 1;
}
function timer() {
if (!interval) {
interval = self.setInterval(changeLights, 1000);
}
}
function stopTimer() {
self.clearInterval(interval);
interval = null;
}
<!DOCTYPE html>
<html>
<body>
<h1>Traffic Lights</h1>
<img id="redImg" src="red.png" alt="Red traffic light" />
<p>
<button type="button" onclick="timer()">Start Lights</button>
<button type="button" onclick="stopTimer()">Stop Lights</button>
</p>
</body>
</html>
请注意,我在某些方面更改了它,最明显的是删除了与toggle
有关的代码。此版本还允许您在不重新加载页面的情况下再次启动它,并阻止您启动多个间隔,这将需要重新加载页面以停止。