尝试制作自动交通灯

Trying to make automated traffic lights

嗨,我正在尝试制作一组​​自动交通信号灯,但我无法让它们停止 运行。我试过使用 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>

尝试将间隔设置为全局变量。您还需要调用 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 有关的代码。此版本还允许您在不重新加载页面的情况下再次启动它,并防止您启动多个间隔,这需要重新加载页面才能停止。