2016-11-27 10 views
1

私はjavascriptを使用して信号機システムを作って、setIntervalを使ってそれ自体を動かしましたが、どのようにタイミングを変えることができますか?例えば、私は赤色の光と緑色の光を琥珀色と赤色の琥珀色より長く長持ちさせたいと思います。JavaScript Traffic light system 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

非常に簡単な解決策は、言って間隔を設定した後、1000msの長い可視であるべきである配列の色を繰り返すことであろう。 – 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>

関連する問題