|
@@ -0,0 +1,79 @@
|
|
|
+// Async/Await Homework 2
|
|
|
+// Светофор
|
|
|
+const delay = ms => new Promise(ok => setTimeout(() => ok(ms), ms))
|
|
|
+const red = document.querySelector('.red')
|
|
|
+const yellow = document.querySelector('.yellow')
|
|
|
+const green = document.querySelector('.green')
|
|
|
+
|
|
|
+async function trafficLight() {
|
|
|
+ while (true) {
|
|
|
+ changeLight(green)
|
|
|
+ await delay(3000)
|
|
|
+ changeLight(red)
|
|
|
+ await delay(3000)
|
|
|
+ changeLight(yellow)
|
|
|
+ await delay(3000)
|
|
|
+ }
|
|
|
+}
|
|
|
+trafficLight()
|
|
|
+
|
|
|
+function changeLight(color) {
|
|
|
+ if (color !== red && color !== yellow) {
|
|
|
+ red.style.opacity = .2
|
|
|
+ yellow.style.opacity = .2
|
|
|
+ green.style.opacity = 1
|
|
|
+ } if (color !== red && color !== green) {
|
|
|
+ red.style.opacity = .2
|
|
|
+ yellow.style.opacity = 1
|
|
|
+ green.style.opacity = .2
|
|
|
+ }
|
|
|
+ if (color !== yellow && color !== green) {
|
|
|
+ red.style.opacity = 1
|
|
|
+ yellow.style.opacity = .2
|
|
|
+ green.style.opacity = .2
|
|
|
+ }
|
|
|
+}
|
|
|
+
|
|
|
+// PedestrianTrafficLight
|
|
|
+const red1 = document.querySelector('.red1')
|
|
|
+const green1 = document.querySelector('.green1')
|
|
|
+let btn1 = document.querySelector('.btn1')
|
|
|
+async function PedestrianTrafficLight() {
|
|
|
+ while (true) {
|
|
|
+ changePedestrianTrafficLight(red1)
|
|
|
+ await Promise.race([delay(4100), new Promise((ok) => btn1.onclick = ok)])
|
|
|
+ changePedestrianTrafficLight(green1)
|
|
|
+ await Promise.race([delay(4100), new Promise((ok) => btn1.onclick = ok)])
|
|
|
+ }
|
|
|
+}
|
|
|
+PedestrianTrafficLight()
|
|
|
+
|
|
|
+btn1.addEventListener('click', () => {
|
|
|
+ changeLight(red);
|
|
|
+ changePedestrianTrafficLight(green1);
|
|
|
+ btn1.disabled = true;
|
|
|
+ setTimeout(() => { btn1.disabled = false }, 10000);
|
|
|
+})
|
|
|
+
|
|
|
+function changePedestrianTrafficLight(color1) {
|
|
|
+ if (color1 !== red1) {
|
|
|
+ red1.style.opacity = .2
|
|
|
+ green1.style.opacity = 1
|
|
|
+ }
|
|
|
+ if (color1 !== green1) {
|
|
|
+ red1.style.opacity = 1
|
|
|
+ green1.style.opacity = .2
|
|
|
+ }
|
|
|
+}
|
|
|
+
|
|
|
+// domEventPromise
|
|
|
+let btn = document.querySelector('.btn')
|
|
|
+function domEventPromise(button, eventName) {
|
|
|
+ return new Promise(res => {
|
|
|
+ button.addEventListener(eventName, (e) => res(e))
|
|
|
+ button.removeEventListener(eventName, (e) => res(e))
|
|
|
+ });
|
|
|
+}
|
|
|
+domEventPromise(btn, 'click')
|
|
|
+ .then(e => console.log('event click happens', e)).then(e => (btn.disabled = true, e))
|
|
|
+
|