script.js 2.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778
  1. const delay = ms => new Promise(ok => setTimeout(() => ok(ms), ms))
  2. async function trafficLight(dom) {
  3. dom = document.getElementById('light1')
  4. let green = document.getElementById('green')
  5. let red = document.getElementById('red')
  6. let yellow = document.getElementById('yellow')
  7. while (true) {
  8. red.style.visibility = 'visible'
  9. green.style.visibility = 'hidden'
  10. yellow.style.visibility = 'hidden'
  11. await delay(3000)
  12. yellow.style.visibility = 'visible'
  13. green.style.visibility = 'hidden'
  14. red.style.visibility = 'hidden'
  15. await delay(1000)
  16. green.style.visibility = 'visible'
  17. red.style.visibility = 'hidden'
  18. yellow.style.visibility = 'hidden'
  19. await delay(3000)
  20. yellow.style.visibility = 'visible'
  21. green.style.visibility = 'hidden'
  22. red.style.visibility = 'hidden'
  23. await delay(1000)
  24. }
  25. }
  26. trafficLight();
  27. //trafficLight2
  28. function domEventPromise(element, eventName) {
  29. return new Promise((resolve, reject) => {
  30. element.addEventListener(eventName, (e) => {
  31. resolve(e)
  32. trafficLight2(e)
  33. })
  34. element.removeEventListener(eventName, (e) => {
  35. resolve(e)
  36. trafficLight2(e)
  37. })
  38. })
  39. }
  40. async function trafficLight2() {
  41. while (true) {
  42. if (true) {
  43. red1.style.visibility = "hidden";
  44. green1.style.visibility = "visible";
  45. btn.disabled = true;
  46. await delay(4000);
  47. btn.disabled = false;
  48. await Promise.race([
  49. delay(1000),
  50. domEventPromise(btn, "click").then((e) =>
  51. console.log("event click happens", e)
  52. ),
  53. ]);
  54. }
  55. if (true) {
  56. btn.disabled = true;
  57. green1.style.visibility = "hidden";
  58. red1.style.visibility = "visible";
  59. await delay(5000);
  60. }
  61. }
  62. }
  63. trafficLight2()