Js-HW14.js 2.3 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192
  1. const delay = ms => new Promise(ok => setTimeout(() => ok(ms), ms))
  2. const red = document.querySelector('.red')
  3. const yellow = document.querySelector('.yellow')
  4. const green = document.querySelector('.green')
  5. let col = red
  6. // async function trafficLight(){
  7. // while (true){
  8. // changeLight(green)
  9. // await delay(3000)
  10. // changeLight(yellow)
  11. // await delay(2000)
  12. // changeLight(red)
  13. // await delay(3000)
  14. // }
  15. // }
  16. // trafficLight().then()
  17. function changeLight(color) {
  18. if(col !== color) {
  19. col.style.opacity = .2
  20. color.style.opacity = 1
  21. col = color
  22. } else {
  23. color.style.opacity = 1
  24. }
  25. }
  26. let btn = document.querySelector('.btn')
  27. function domEventPromise(button, eventName) {
  28. return new Promise(res => {
  29. button.addEventListener(eventName, (e) => res(e))
  30. button.removeEventListener(eventName, (e) => res(e))
  31. });
  32. }
  33. domEventPromise(btn, 'click')
  34. .then(e => console.log('event click happens', e))
  35. let stopLightIsActive = true
  36. async function pedestrianTrafficLight() {
  37. while(stopLightIsActive){
  38. changeLight(red)
  39. await delay(100)
  40. }
  41. }
  42. pedestrianTrafficLight().then()
  43. btn.addEventListener('click', async () => {
  44. stopLightIsActive = !stopLightIsActive
  45. await delay(3000)
  46. changeLight(yellow)
  47. await delay(1000)
  48. changeLight(green)
  49. await delay(4000)
  50. changeLight(yellow)
  51. await delay(1000)
  52. changeLight(red)
  53. })
  54. async function speedtest(getPromise, count, parallel = 1) {
  55. let time = performance.now();
  56. let promisesArr = [];
  57. let initParallel = parallel;
  58. for (let i = 0; i < count; i++) {
  59. promisesArr.push(getPromise);
  60. parallel--;
  61. await Promise.all(promisesArr);
  62. }
  63. time = performance.now() - time;
  64. return {
  65. duration: time,
  66. querySpeed: count / time,
  67. queryDuration: time / count,
  68. parallelSpeed: (count / time) * initParallel,
  69. parallelDuration: time / (count * initParallel),
  70. };
  71. }
  72. speedtest(() => delay(1000), 10, 10).then((res) =>console.log(res));
  73. speedtest(
  74. () =>
  75. fetch("http://swapi.dev/api/people/1").then((res) =>
  76. res.json()
  77. ),
  78. 2,
  79. 2
  80. ).then((v)=>console.log(v))