Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

[js] 第111天 请用js编写一个红绿灯程序 #1027

Open
haizhilin2013 opened this issue Aug 4, 2019 · 17 comments
Open

[js] 第111天 请用js编写一个红绿灯程序 #1027

haizhilin2013 opened this issue Aug 4, 2019 · 17 comments
Labels
js JavaScript

Comments

@haizhilin2013
Copy link
Collaborator

第111天 请用js编写一个红绿灯程序

@haizhilin2013 haizhilin2013 added the js JavaScript label Aug 4, 2019
@LinStan
Copy link

LinStan commented Aug 5, 2019

基于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()

@haizhilin2013
Copy link
Collaborator Author

@LinStan 你写的红绿灯估计一般的车辆过不去啊

@LinStan
Copy link

LinStan commented Aug 5, 2019

@haizhilin2013 哈哈哈,油门踩死不带怕的。
大佬 补了个Promise的。帮我看下有没有毛病,Promise和SetTimeout折腾了会

@xxf1996
Copy link

xxf1996 commented Aug 5, 2019

咋一看题目我还以为是设计十字路口红路灯算法那种,那可是有点复杂: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)

@nowherebutup
Copy link

nowherebutup commented Aug 5, 2019

  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();

@DarthVaderrr
Copy link

@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()

@bestvow
Copy link

bestvow commented Aug 5, 2019

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()

@NicholasBaiYa
Copy link

NicholasBaiYa commented Aug 6, 2019

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)
    }
}

@Tttst00001
Copy link

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)

@AruthlessMachine
Copy link

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] )

@AruthlessMachine
Copy link


aaa

@rni-l
Copy link

rni-l commented Jan 28, 2020

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()

@hellochenk
Copy link

<!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>

粘到html用浏览器打开

@maoxiaoxing
Copy link

这道题应该考察的是宏任务, 下面是一个不太成熟的实现

function fn() {
    console.log('绿灯')
    setTimeout(() => {
      console.log('黄灯')
      setTimeout(() => {
        console.log('红灯')
        setTimeout(() => {
          fn()
        }, 2000)
      }, 2000)
    }, 2000)
  }
  fn()

@wepn13232
Copy link

wepn13232 commented Jan 15, 2021

随便搞了一个

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();

@HughDai
Copy link

HughDai commented Aug 30, 2021

generator实现

function print (light) {
  console.log('%c%s', `color: ${light.color};background:black;`, light.color)
  // return sleep(light.duration)
  return new Promise(resolve => {
      setTimeout(resolve, light.duration)
  })
}

function* trafficLight () {
  var lights = [
      { color: 'red', duration: 3000 },
      { color: 'yellow', duration: 2000 },
      { color: 'green', duration: 1000 },
  ]
  for (var i = 0; i < lights.length; i++) {
      yield print(lights[i])
   }
}

function main () {
  var gen = trafficLight()
  var result = {}
  !function run () {
      result = gen.next()
      console.log(result)
      if(result.done) {
         main()
      } else {
          result.value.then(run)
      }
  }()   
}

main()

@xiaoqiangz
Copy link

function sleep(color, times) {
return new Promise((resolve)=> {
setTimeout(()=> {
resolve()
console.log(现在是信号灯颜色是:${color})
}, times)
})
}

async function run() {
while(true) {
await sleep('red', 5000)
await sleep('yellow', 2000)
await sleep('green', 5000)
}
}
run()

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
js JavaScript
Projects
None yet
Development

No branches or pull requests