index.js 2.5 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394
  1. const delay = ms => new Promise(ok => setTimeout(() => ok(ms), ms))
  2. async function trafficLight(dom){
  3. dom = document.getElementById('color')
  4. let red = document.getElementById('red')
  5. let yellow = document.getElementById('yellow')
  6. let green = document.getElementById('green')
  7. let redTimer = document.getElementById('redTimer')
  8. let greenTimer = document.getElementById('greenTimer')
  9. while (true){
  10. await delay(500)
  11. .then(() => red.style.opacity = 1)
  12. await delay(10000)
  13. .then(() => red.style.opacity = 0.3)
  14. .then(timer(10, redTimer))
  15. await delay(500)
  16. .then(() => yellow.style.opacity = 1)
  17. await delay(1000)
  18. .then(() => yellow.style.opacity = 0.3)
  19. await delay(500)
  20. .then(() => green.style.opacity = 1)
  21. await delay(10000)
  22. .then(() => green.style.opacity = 0.3)
  23. .then(timer(10, greenTimer))
  24. await delay(500)
  25. .then(() => yellow.style.opacity = 1)
  26. await delay(1000)
  27. .then(() => yellow.style.opacity = 0.3)
  28. }
  29. }
  30. async function humanTrafficLight(dom){
  31. dom = document.getElementById('humanColor')
  32. let red = document.getElementById('humanRed')
  33. let green = document.getElementById('humanGreen')
  34. let btn = document.getElementById('btn')
  35. let redTimer = document.getElementById('humanRedTimer')
  36. let greenTimer = document.getElementById('humanGreenTimer')
  37. while (true){
  38. await delay(500)
  39. .then(() => green.style.opacity = 1)
  40. await delay(10000)
  41. .then(() => green.style.opacity = 0.3)
  42. .then(timer(10, greenTimer))
  43. await delay(1500)
  44. await delay(500)
  45. .then(() => red.style.opacity = 1)
  46. await delay(10000)
  47. .then(() => red.style.opacity = 0.3)
  48. .then(timer(10, redTimer))
  49. await delay(1500)
  50. }
  51. }
  52. async function timer(time, value) {
  53. for (time; time> 0; time--){
  54. value.innerHTML = time
  55. await delay(1000)
  56. value.innerHTML = ""
  57. }
  58. }
  59. trafficLight()
  60. humanTrafficLight()
  61. function domEventPromise(click, eventName) {
  62. return new Promise((resolve, reject) => {
  63. click.addEventListener(eventName, (e) => {
  64. resolve(e)
  65. })
  66. click.removeEventListener(eventName, (e) => {
  67. resolve(e)
  68. })
  69. })
  70. }
  71. btn.onclick = () => domEventPromise(btn, 'click').then( e => console.log('event click happens', e))