hw_18_01_flash.html 1.2 KB

123456789101112131415161718192021222324252627282930313233343536
  1. <header>Flash people</header>
  2. <body>
  3. <div id="red">Red</div><br>
  4. <div id="yellow">Yellow</div><br>
  5. <div id="green">Green</div><br>
  6. <script>
  7. const delay = ms => new Promise(ok => setTimeout(() => ok(ms), ms))
  8. function domEventPromise(elem, event) {
  9. return new Promise((resolve, reject) => {
  10. elem.addEventListener(event, () => resolve(true))
  11. })
  12. }
  13. async function trafficLight(...lights) {
  14. let prevLight = undefined;
  15. let i = 0;
  16. let direction = 1;
  17. while (true) {
  18. let light = lights[i];
  19. if (prevLight)
  20. prevLight.el.style.backgroundColor = "black";
  21. light.el.style.backgroundColor = light.color;
  22. prevLight = light;
  23. await delay(light.delay);
  24. if (i == lights.length - 1)
  25. direction = -1;
  26. else if (i == 0)
  27. direction = 1;
  28. i += direction;
  29. }
  30. }
  31. trafficLight({ el: red, color: "red", delay: 2000 }, { el: yellow, color: "yellow", delay: 2000 }, { el: green, color: "green", delay: 2000 });
  32. </script>
  33. </body>