main.js 1.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960
  1. const delay = ms => new Promise(ok => setTimeout(() => ok(ms), ms))
  2. const red = document.querySelector('.red')
  3. const yellow = document.querySelector('.yellow')
  4. const green = document.querySelector('.green')
  5. let col = red
  6. // async function trafficLight(){
  7. // while (true){
  8. // changeLight(green)
  9. // await delay(3000)
  10. // changeLight(yellow)
  11. // await delay(2000)
  12. // changeLight(red)
  13. // await delay(3000)
  14. // }
  15. // }
  16. // trafficLight().then()
  17. function changeLight(color) {
  18. if(col !== color) {
  19. col.style.opacity = .2
  20. color.style.opacity = 1
  21. col = color
  22. } else {
  23. color.style.opacity = 1
  24. }
  25. }
  26. let btn = document.querySelector('.btn')
  27. function domEventPromise(button, eventName) {
  28. return new Promise(res => {
  29. button.addEventListener(eventName, (e) => res(e))
  30. button.removeEventListener(eventName, (e) => res(e))
  31. });
  32. }
  33. domEventPromise(btn, 'click')
  34. .then(e => console.log('event click happens', e))
  35. let stopLightIsActive = true
  36. async function pedestrianTrafficLight() {
  37. while(stopLightIsActive){
  38. changeLight(red)
  39. await delay(100)
  40. }
  41. }
  42. pedestrianTrafficLight().then()
  43. btn.addEventListener('click', async () => {
  44. stopLightIsActive = !stopLightIsActive
  45. await delay(3000)
  46. changeLight(yellow)
  47. await delay(1000)
  48. changeLight(green)
  49. await delay(4000)
  50. changeLight(yellow)
  51. await delay(1000)
  52. changeLight(red)
  53. });