帮助重置setTimeOut在javascript中制作交通灯

Help Reset setTimeOut for make a Traffic Light in javascript

本文关键字:javascript setTimeOut 帮助      更新时间:2023-09-26

我想让交通信号灯自动工作,就像我做的一样,但在19之后,它将重置并重新开始功能所以它会像交通灯一样永不停止,并且会重复他的自我

    1. 红灯10秒
  • 2秒黄灯
  • 6秒绿灯
  • 1秒黄灯
  • 和遣返回国 ........
谢谢你的帮助!!

 function changecolor(){
var red = document.querySelector('#Red')	
var yellow = document.querySelector('#Yellow')	
var green = document.querySelector('#Green')	
	
setTimeout(function(){ red.style.background= "red" },5);	// on red
setTimeout(function(){ yellow.style.background= "yellow"  //on yellow + off red
red.style.background= "#FF4A4D" 
},10000);	
setTimeout(function(){ yellow.style.background= "#F1FF73"  //on green + off yellow
green.style.background= "green"
},12000);	
setTimeout(function(){ yellow.style.background= "yellow" //on yellow + off green
green.style.background= "#43B560"
 },18000);	
setTimeout(function(){ red.style.background= "red" //off yellow + on red 
yellow.style.background= "#F1FF73"
 },19000);	
 setTimeout(changecolor(), 19005);
	
}
body{
width:100%;
height:100%;
margin: 0 auto;
}
h1{
margin-left:45%;
}
button{
margin-left:49%;
margin-top:2%;
color:white;
border: 1px solid blue;
background:black;
}
#Red{
display:block;
background:#FF4A4D;
width:15%;
height:20vh;
border-radius:50%;
margin-left:45%;
margin-top:1%;
}
#Yellow{
display:block;
background:#F1FF73;
width:15%;
height:20vh;
border-radius:50%;
margin-left:45%;
margin-top:1%;
}
#Green{
display:block;
background:#43B560;
width:15%;
height:20vh;
border-radius:50%;
margin-left:45%;
margin-top:1%;
}
<!DOCTYPE HTML>
<html lang="en-US">
<head>
	<meta charset="UTF-8">
	<script type="text/javascript" src="js/script.js"></script>
	<link rel="stylesheet" href="css/style.css" />
	<title>Traffic Light</title>
</head>
<body>
	<h1>Traffic Light</h1>
	<div id="Red"></div>
	<div id="Yellow"></div>
	<div id="Green"></div>
	<button onclick="changecolor()">Click To Start</button>
	
</body>
</html>

看一下这个例子。

function changecolor(){
var red = document.querySelector('#Red')    
var yellow = document.querySelector('#Yellow')  
var green = document.querySelector('#Green')    
if(time == 20) {
     red.style.background= "red";
     yellow.style.background = "#F1FF73";
     time = 1;
}
if(time % 10 == 0) {
     yellow.style.background= "yellow"
     red.style.background= "#FF4A4D" 
}
 if(time % 12 == 0) {
     green.style.background= "green";
     yellow.style.background = "#F1FF73";
}   
 if(time % 18 == 0) {
     yellow.style.background= "yellow" //on yellow + off green
     green.style.background= "#43B560"
}   
 if(time % 19 == 0) {
      red.style.background= "red" //off yellow + on red 
      yellow.style.background= "#F1FF73"
}   
 time+=1;
}