第111天 请用js编写一个红绿灯程序
基于setInterval实现
var n = 0;
function setColor () {
if (n % 3 == 0) { console.log('red') }
else if (n % 3 == 1) { console.log('yellow') }
else { console.log('green') }
n++;
}
setInterval(function () { setColor() }, 1000);
Promise
async function ryg (color, duration) {
console.log(color)
await new Promise(function (resolve) {
setTimeout(resolve, duration);
})
}
async function run () {
while (true) {
await ryg('red', 1000)
await ryg('yellow', 2000)
await ryg('green', 5000)
}
}
run()
@LinStan 你写的红绿灯估计一般的车辆过不去啊
@haizhilin2013 哈哈哈,油门踩死不带怕的。
大佬 补了个Promise的。帮我看下有没有毛病,Promise和SetTimeout折腾了会
咋一看题目我还以为是设计十字路口红路灯算法那种,那可是有点复杂:smile: ;看了上面的才知道原来是循环显示红绿灯……
function sleep (t) {
return new Promise((resolve, reject) => {
setTimeout(() => {
resolve()
}, t)
})
}
/**
* 循环显示红绿灯
* @param {number} green 绿灯显示毫秒数
* @param {number} yellow 黄灯显示毫秒数
* @param {number} red 红灯显示毫秒数
*/
async function light (green = 15000, yellow = 3000, red = 10000) {
let status = 'green'
while (true) {
await sleep(green).then(() => {
status = 'yellow'
console.log(status)
})
await sleep(yellow).then(() => {
status = 'red'
console.log(status)
})
await sleep(red).then(() => {
status = 'green'
console.log(status)
})
}
}
light(3000, 1000, 1000)
function foo(light){
return new Promise((resolve,reject)=>{
setTimeout(() => {
console.log(light);
resolve();
}, 1000);
})
}
async function run(){
await foo('red');
await foo('green');
await foo('blue');
setTimeout(run, 0);
}
run();
@LinStan 酱紫
function ryg(color, duration) {
return new Promise(function (resolve) {
setTimeout(resolve.bind(this, color), duration);
})
}
async function run() {
let light;
while (true) {
light = await ryg('red', 1000)
console.log(light)
light = await ryg('yellow', 2000)
console.log(light)
light = await ryg('green', 200)
console.log(light)
}
}
run()
function main(index) {
const lights = ['red', 'yellow', 'green']
setTimeout(() => {
console.log(lights[index % 3])
it.next()
}, 1000)
}
function* run(times = 3) {
let init = 0
while (init < times) {
yield main(init++)
}
}
const it = run()
it.next()
let line = (e) => {
if (e == 1) {
console.log('黄灯')
setTimeout(() => { line() }, 1000)
} else if (e == 2) {
console.log('绿灯')
setTimeout(() => { line(1) }, 2000)
} else {
console.log('红灯')
setTimeout(() => { line(2) }, 2000)
}
}
var time = 10
var color = 'red'
function timing () {
time--
console.log(time, color)
if (time === 0) {
time = 11
if (color === 'red') {
setTimeout(function () {
color = 'green'
}, 2000)
color = 'yellow'
} else {
color = 'red'
}
}
}
setInterval('timing()', 1000)
class TrafficLight {
constructor( arr ){
this.time = 0
this.index = 0
this.colors= ['red','green', 'yellow']
this.timeLens = arr
this.timer = ''
this.state = ''
this.init()
}
init(){
this.time = this.timeLens[0]
this.state = this.colors[0]
this.run()
}
run(){
console.log( this.state, this.time )
this.timer = setInterval(()=>{
if(this.time <= 1) {
clearInterval(this.timer)
this.index = (this.index+1)%3
this.time = this.timeLens[ this.index ]
this.state = this.colors[ this.index ]
this. run()
return
}
this.time -= 1
console.log( this.state, this.time )
},1000)
}
}
new TrafficLight( [6,3,1] )
function trafficLight() {
const light = ['red', 'yellow', 'green']
let index = 0
const times = [2000, 500, 3000]
function start(_time) {
setTimeout(() => {
index += 1
if (index >= times.length) {
index = 0
}
console.log(light[index])
start(times[index])
}, _time);
}
console.log(light[index])
start(times[index])
}
trafficLight()
<!DOCTYPE html>
<html>
<head>
<title>honglvdeng </title>
<style type="text/css">
* {
margin: 0;
padding: 0;
box-sizing: border-box;
}
.coloum div {
text-align: center;
margin: 0 auto;
}
.box div {
width: 50px;
height: 50px;
border-radius: 50%;
opacity: 0.3;
}
.red {
background: red;
}
.yellow {
background: yellow;
}
.green {
background: green;
}
</style>
</head>
<body>
<div class='root'>
<div class='box coloum'>
<div class='red'></div>
<div class='yellow'></div>
<div class='green'></div>
</div>
<div class='box horizon'>
<div class='red'></div>
<div class='yellow'></div>
<div class='green'></div>
</div>
</div>
</body>
<script type="text/javascript">
// 通行时长
const long = {
allow: 10,
warning: 3
}
// key2val
const key2val = {
coloum: 'coloum',
horizon: 'horizon'
}
const timeType = {
allow: 'allow',
warning: 'warning'
}
// 当前方向
let current = {
type: key2val.coloum,
time: timeType.allow,
long: long.allow
};
let timer = null
// child list
const coloum = document.getElementsByClassName('coloum')[0].children;
const horizon = document.getElementsByClassName('horizon')[0].children;
const clearNode = () => {
coloum[0].style.opacity = 0.3;
coloum[1].style.opacity = 0.3;
coloum[2].style.opacity = 0.3;
horizon[0].style.opacity = 0.3;
horizon[1].style.opacity = 0.3;
horizon[2].style.opacity = 0.3;
}
// 南北通行
const showns = () => {
coloum[2].style.opacity = 1;
horizon[0].style.opacity = 1;
}
// 东西通行
const showew = () => {
coloum[0].style.opacity = 1;
horizon[2].style.opacity = 1;
}
const warningns = () => {
coloum[1].style.opacity = 1;
horizon[0].style.opacity = 1;
}
const warningew = () => {
coloum[0].style.opacity = 1;
horizon[1].style.opacity = 1;
}
const run = (currt) => {
clearNode();
timer = null;
switch(currt.type) {
// 东西
case key2val.coloum:
if(currt.time === timeType.allow) {
console.log('南北绿灯')
// 允许 通行
showns();
const t = currt.long;
currt = {
type: key2val.coloum,
time: timeType.warning,
long: long.warning
}
timer = setTimeout(() => run(currt), t *1000)
// setTimeout(() => console.log(currt), currt.long *1000)
} else {
console.log('南北黄灯')
// 警告
warningns();
const t = currt.long;
currt = {
type: key2val.horizon,
time: timeType.allow,
long: long.allow
}
timer = setTimeout(() => run(currt), t *1000)
}
break;
// 南北
case key2val.horizon:
if(currt.time === timeType.allow) {
console.log('东西绿灯')
// 允许 通行
showew();
const t = currt.long;
currt = {
type: key2val.horizon,
time: timeType.warning,
long: long.warning
}
timer = setTimeout(() => run(currt), t *1000)
} else {
console.log('东西黄灯')
// 警告
warningew();
const t = currt.long;
currt = {
type: key2val.coloum,
time: timeType.allow,
long: long.allow
}
timer = setTimeout(() => run(currt), t *1000)
}
break;
}
}
run(current);
</script>
</html>
这道题应该考察的是宏任务, 下面是一个不太成熟的实现
function fn() {
console.log('绿灯')
setTimeout(() => {
console.log('黄灯')
setTimeout(() => {
console.log('红灯')
setTimeout(() => {
fn()
}, 2000)
}, 2000)
}, 2000)
}
fn()
随便搞了一个
function changeLight(light, time) {
return new Promise(resolve => {
console.log('现在为:', light);
setTimeout(() => {
resolve();
}, time);
})
}
async function trafficLight() {
await changeLight('red', 3000);
await changeLight('yellow', 1000);
await changeLight('green', 3000);
await changeLight('yellow',1000).then(()=>{
trafficLight()
})
}
trafficLight();
Most helpful comment
咋一看题目我还以为是设计十字路口红路灯算法那种,那可是有点复杂:smile: ;看了上面的才知道原来是循环显示红绿灯……