这是我的交通信号灯代码。我想知道如何添加计时器以每3秒更改一次交通灯的颜色,例如,单击按钮时。谢谢!

<!DOCTYPE html>
<html>
<body>
  <h1>JavaScript Task 3</h1>
  <p>This is  my Traffic Light script</p>
  <img id="light" src="./assets/red.jpg">
  <button type="button" onclick="changeLights()">Change Lights</button>
  <script>
    var list = ["./assets/red.jpg","./assets/redamber.jpg", "./assets/green.jpg","./assets/amber.jpg" ];
    var index = 0;
    function changeLights() {
      index = index + 1;
      if (index == list.length)
        index = 0;
      var image = document.getElementById('light');
      image.src = list[index];
    }
  </script>
</body>
</html>

最佳答案

使用setInterval功能。

第一个参数是您要调用的函数,第二个参数是应调用的频率(以毫秒为单位)。

var timer = setInterval(changeLights,3000);




var list = ["./assets/red.jpg","./assets/redamber.jpg",     "./assets/green.jpg","./assets/amber.jpg" ];
var index = 0;
function changeLights() {
     index = index + 1;
if (index == list.length)
index = 0;
var image = document.getElementById('light');
image.src=list[index]; }
  var timer = setInterval(changeLights,3000);

<h1>JavaScript Task 3</h1>
<p>This is  my Traffic Light script</p>
<img id="light" src="./assets/red.jpg"> <button type="button"
onclick="changeLights()">Change Lights</button>  

关于javascript - 交通灯序列Javascript,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/36920320/

10-12 00:21