HW18_PedestrianTrafficLight.html 2.1 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091
  1. <!DOCTYPE html>
  2. <html lang="en">
  3. <head>
  4. <meta charset="UTF-8">
  5. <meta http-equiv="X-UA-Compatible" content="IE=edge">
  6. <meta name="viewport" content="width=device-width, initial-scale=1.0">
  7. <title>Document</title>
  8. <style>
  9. #traffic-light {
  10. border: 2px solid black;
  11. padding: 20px;
  12. border-radius: 50px;
  13. width: min-content;
  14. }
  15. #color-red,
  16. #color-green {
  17. width: 100px;
  18. height: 100px;
  19. border-radius: 50%;
  20. border: 10px solid black;
  21. margin-bottom: 10px;
  22. background-color: transparent;
  23. }
  24. #btn {
  25. padding: 5px 25px;
  26. font-size: 1.2em;
  27. min-width: 164px;
  28. margin-top: 20px;
  29. }
  30. </style>
  31. </head>
  32. <body>
  33. <div id="traffic-light">
  34. <div id="color-red">
  35. </div>
  36. <div id="color-green">
  37. </div>
  38. </div>
  39. <button id="btn" type="button">Зеленый</button>
  40. </body>
  41. <script>
  42. const delay = ms => new Promise(ok => setTimeout(() => ok(ms), ms))
  43. function domEventPromise(element, nameOfEvent) {
  44. function executor(resolve) {
  45. function event(param) {
  46. element.disabled = true
  47. element.removeEventListener(nameOfEvent, event)
  48. }
  49. element.disabled = false
  50. element.addEventListener(nameOfEvent, event)
  51. }
  52. return new Promise(executor)
  53. }
  54. async function pedestrianTrafficLight(ms) {
  55. while (true) {
  56. const red = document.getElementById('color-red')
  57. red.style.backgroundColor = 'red'
  58. await Promise.race([
  59. delay(ms),
  60. domEventPromise(document.getElementById('btn'), 'click')
  61. ])
  62. red.style.backgroundColor = 'transparent'
  63. const green = document.getElementById('color-green')
  64. green.style.backgroundColor = 'green'
  65. await delay(ms)
  66. green.style.backgroundColor = 'transparent'
  67. }
  68. }
  69. pedestrianTrafficLight(6000)
  70. </script>
  71. </html>