trafficLight-stage2.js 1.1 KB

1234567891011121314151617181920212223242526272829303132333435363738
  1. const delay = ms => new Promise(ok => setTimeout(() => ok(ms), ms));
  2. const toggleLight = (switcher, className) => {
  3. const element = document.querySelector(className).classList;
  4. switcher ? element.add('on') : element.remove('on');
  5. }
  6. const addDomElement = (element) => {
  7. for(let i = 1; i <= 3; i++) {
  8. const domElement = document.createElement(element);
  9. domElement.classList.add('traffic-light__element');
  10. if(i === 1) {
  11. domElement.classList.add('green');
  12. } else if (i === 2) {
  13. domElement.classList.add('yellow');
  14. } else {
  15. domElement.classList.add('red');
  16. }
  17. trafficLightId.appendChild(domElement);
  18. }
  19. }
  20. const trafficLight = async (domElement, delayGreen, delayYellow, delayRed) =>{
  21. addDomElement(domElement);
  22. while (true){
  23. toggleLight(false,'.red');
  24. toggleLight(true,'.green');
  25. await delay(delayGreen);
  26. toggleLight(false,'.green');
  27. toggleLight(true,'.yellow');
  28. await delay(delayYellow);
  29. toggleLight(false,'.yellow');
  30. toggleLight(true,'.red');
  31. await delay(delayRed);
  32. }
  33. }
  34. trafficLight('div',2000, 4000, 6000);