123456789101112131415161718192021222324252627282930313233343536 |
- <header>Flash people</header>
- <body>
- <div id="red">Red</div><br>
- <div id="yellow">Yellow</div><br>
- <div id="green">Green</div><br>
- <script>
- const delay = ms => new Promise(ok => setTimeout(() => ok(ms), ms))
- function domEventPromise(elem, event) {
- return new Promise((resolve, reject) => {
- elem.addEventListener(event, () => resolve(true))
- })
- }
- async function trafficLight(...lights) {
- let prevLight = undefined;
- let i = 0;
- let direction = 1;
- while (true) {
- let light = lights[i];
- if (prevLight)
- prevLight.el.style.backgroundColor = "black";
- light.el.style.backgroundColor = light.color;
- prevLight = light;
- await delay(light.delay);
- if (i == lights.length - 1)
- direction = -1;
- else if (i == 0)
- direction = 1;
- i += direction;
- }
- }
- trafficLight({ el: red, color: "red", delay: 2000 }, { el: yellow, color: "yellow", delay: 2000 }, { el: green, color: "green", delay: 2000 });
- </script>
- </body>
|