hw_18_02_PedestrianTrafficLight.html 2.1 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849
  1. <header>PedestrianTrafficLight</header>
  2. <body>
  3. <div id="red" style="background-color: red">Red</div><br>
  4. <div id="green" style="background-color: black;">Green</div><br>
  5. <button id="btn">GO</button>
  6. <script>
  7. const delay = ms => new Promise(ok => setTimeout(() => ok(ms), ms))
  8. async function trafficLight(red, green, goBtn, cycDelay, pressPeriod) {
  9. let isRed = true;
  10. let lastBtnPress = undefined;
  11. let btnPress = domEventPromise(goBtn, 'click');
  12. function domEventPromise(element, eventName) {
  13. function executor(resolve) {
  14. function myOnClick(event) {
  15. element.removeEventListener(eventName, myOnClick);
  16. btnPress = domEventPromise(goBtn, 'click');
  17. resolve({ isRed: false, isButton: true });
  18. }
  19. element.addEventListener(eventName, myOnClick);
  20. }
  21. return new Promise(executor);
  22. }
  23. while (true) {
  24. let cycle = new Promise(
  25. async resolve => {
  26. await delay(cycDelay);
  27. resolve({ isRed: !isRed, isButton: false });
  28. });
  29. let res = await Promise.race([cycle, btnPress]);
  30. if (res.isButton) {
  31. let isSkipButton = !isRed || (lastBtnPress && (new Date() - lastBtnPress) < pressPeriod);
  32. if (isSkipButton)
  33. res = await cycle;
  34. lastBtnPress = new Date();
  35. }
  36. isRed = res.isRed;
  37. isRed ? enableLight(red, "red", green) : enableLight(green, "green", red);
  38. }
  39. }
  40. const enableLight = (fireElement, color, disFlashElement) => {
  41. fireElement.style.backgroundColor = color;
  42. disFlashElement.style.backgroundColor = "black";
  43. }
  44. let cycDelay = 5000;
  45. trafficLight(red, green, btn, cycDelay, cycDelay / 2 * 3);
  46. </script>
  47. </body>