main.js 2.2 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879
  1. // Async/Await Homework 2
  2. // Светофор
  3. const delay = ms => new Promise(ok => setTimeout(() => ok(ms), ms))
  4. const red = document.querySelector('.red')
  5. const yellow = document.querySelector('.yellow')
  6. const green = document.querySelector('.green')
  7. async function trafficLight() {
  8. while (true) {
  9. changeLight(green)
  10. await delay(3000)
  11. changeLight(red)
  12. await delay(3000)
  13. changeLight(yellow)
  14. await delay(3000)
  15. }
  16. }
  17. trafficLight()
  18. function changeLight(color) {
  19. if (color !== red && color !== yellow) {
  20. red.style.opacity = .2
  21. yellow.style.opacity = .2
  22. green.style.opacity = 1
  23. } if (color !== red && color !== green) {
  24. red.style.opacity = .2
  25. yellow.style.opacity = 1
  26. green.style.opacity = .2
  27. }
  28. if (color !== yellow && color !== green) {
  29. red.style.opacity = 1
  30. yellow.style.opacity = .2
  31. green.style.opacity = .2
  32. }
  33. }
  34. // PedestrianTrafficLight
  35. const red1 = document.querySelector('.red1')
  36. const green1 = document.querySelector('.green1')
  37. let btn1 = document.querySelector('.btn1')
  38. async function PedestrianTrafficLight() {
  39. while (true) {
  40. changePedestrianTrafficLight(red1)
  41. await Promise.race([delay(4100), new Promise((ok) => btn1.onclick = ok)])
  42. changePedestrianTrafficLight(green1)
  43. await Promise.race([delay(4100), new Promise((ok) => btn1.onclick = ok)])
  44. }
  45. }
  46. PedestrianTrafficLight()
  47. btn1.addEventListener('click', () => {
  48. changeLight(red);
  49. changePedestrianTrafficLight(green1);
  50. btn1.disabled = true;
  51. setTimeout(() => { btn1.disabled = false }, 10000);
  52. })
  53. function changePedestrianTrafficLight(color1) {
  54. if (color1 !== red1) {
  55. red1.style.opacity = .2
  56. green1.style.opacity = 1
  57. }
  58. if (color1 !== green1) {
  59. red1.style.opacity = 1
  60. green1.style.opacity = .2
  61. }
  62. }
  63. // domEventPromise
  64. let btn = document.querySelector('.btn')
  65. function domEventPromise(button, eventName) {
  66. return new Promise(res => {
  67. button.addEventListener(eventName, (e) => res(e))
  68. button.removeEventListener(eventName, (e) => res(e))
  69. });
  70. }
  71. domEventPromise(btn, 'click')
  72. .then(e => console.log('event click happens', e)).then(e => (btn.disabled = true, e))