js.js 1.5 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950
  1. const delay = (ms) => new Promise((ok) => setTimeout(() => ok(ms), ms));
  2. async function trafficLight() {
  3. while (true) {
  4. const green = document.querySelector(".green");
  5. const yellow = document.querySelector(".yellow");
  6. const red = document.querySelector(".red");
  7. green.style.background = "green";
  8. red.style.background = "black";
  9. var numGreen = 5;
  10. const timerGreen = () => {
  11. numGreen--;
  12. numGreen === 0
  13. ? (green.style.color = "black") && (red.style.color = "black")
  14. : setTimeout(timerGreen, 1000) && (green.style.color = "white");
  15. green.innerHTML = numGreen;
  16. };
  17. setTimeout(timerGreen, 1000);
  18. await delay(5000); // включаем зеленый
  19. green.style.background = "black";
  20. yellow.style.background = "yellow";
  21. var numYellow = 3;
  22. const timerYellow = () => {
  23. numYellow--;
  24. numYellow === 0
  25. ? (yellow.style.color = "black")
  26. : setTimeout(timerYellow, 1000) && (yellow.style.color = "white");
  27. yellow.innerHTML = numYellow;
  28. };
  29. setTimeout(timerYellow, 1000);
  30. await delay(3000); // включаем желтый
  31. yellow.style.background = "black";
  32. red.style.background = "red";
  33. var numRed = 7;
  34. const timerRed = () => {
  35. numRed--;
  36. numRed === 0
  37. ? (red.style.color = "black")
  38. : setTimeout(timerRed, 1000) && (red.style.color = "white");
  39. red.innerHTML = numRed;
  40. };
  41. setTimeout(timerRed, 1000);
  42. await delay(7000) // включаем красный
  43. }
  44. }
  45. trafficLight();