2016-11-27 26 views
1

我已经制作了一个使用javascript的交通灯系统,并使用setInterval使它自行走,但是我怎样才能使时间不同?例如,我希望红灯和绿灯长时间保持琥珀色和红琥珀色。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> 
+0

一个非常简单的解决办法是设置间隔地说,1000毫秒,然后重复颜色的数组,应该是可见更长英寸 – axlj

回答

0

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

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); 
 
};
<h1>JavaScript</h1> 
 
<h2>Learning to code</h2> 
 
<div id="traffic"/> 
 
<button type="button" id="btnChangeColors">Start Traffic Light</button>