JavaScript使用setInterval的交通灯系统

时间:2016-11-27 13:04:05

标签: javascript

我使用javascript创建了一个红绿灯系统,并使用setInterval使其自行运行,但是如何才能使时间不同?例如,我希望红灯和绿灯保持更长时间,然后是琥珀色和红色琥珀色。

<!DOCTYPE html>
<html>
<body>
<h1>JavaScript</h1>
<h2>Learning to code</h2>
<p>This is my very first JavaScript task</p>
<img id="traffic" src="red.png">
<button type="button" onclick="dosomething()">something magical will happen if you press me</button>
<script>
var list = ["red.png", "redamber.png", "green.png", "amber.png"];
var index = 0;
var timer = setInterval(dosomething, 3000)

function dosomething(){
    index = index + 1;
    if (index == list.length) index = 0


    var image = document.getElementById('traffic');
    image.src=list[index];

}
</script>
</body>
</html>

1 个答案:

答案 0 :(得分:0)

这是一个使用类似于我在评论中解释的加权时间的示例。我没有图片,所以我用文字替换了它们。

&#13;
&#13;
function changeColors(){
   if (index >= list.length) index = 0; 
   
   let item = list[index];
   
   if (!item.countdown) item.countdown = item.weight - 1;
   else item.countdown = item.countdown - 1;
   
   var image = document.getElementById('traffic');
   image.innerHTML=list[index].color+'-'+item.countdown;
   
   if (item.countdown == 0) index = index + 1;
}

var list = [
  {color:"red.png", weight:1}, 
  {color:"redamber.png", weight:3}, 
  {color:"green.png", weight:2}, 
  {color:"amber.png", weight:1}
];

var index = 0;

let btnChangeColors = document.getElementById('btnChangeColors');

btnChangeColors.onclick = function() {
  var timer = setInterval(changeColors, 1000);
};
&#13;
<h1>JavaScript</h1>
<h2>Learning to code</h2>
<div id="traffic"/>
<button type="button" id="btnChangeColors">Start Traffic Light</button>
&#13;
&#13;
&#13;