123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103 |
- const delay = ms => new Promise(ok => setTimeout(() => ok(ms), ms))
- async function trafficLight(parent, greenDelay, yellowDelay, redDelay) {
- while (true) {
- colorChange(parent, "green", 2)
- await delay(greenDelay)
- colorChange(parent, "yellow", 1)
- await delay(yellowDelay)
- colorChange(parent, "red", 0)
- await delay(redDelay)
- colorChange(parent, "yellow", 1)
- await delay(yellowDelay)
- }
- }
- let colorChange = (parent, color, indexElem) => {
- for (let i = 0; i < parent.children.length; i++) {
- indexElem === i ? parent.children[indexElem].style.background = color : parent.children[i].style.background = "";
- }
- }
- let elemCreator = (parent, element, amount) => {
- for (let i = 0; i < amount; i++) {
- let e = document.createElement(element);
- parent.append(e)
- }
- }
- elemCreator(light, "div", 3)
- trafficLight(light, 6000, 2500, 6000)
- function domEventPromise(element, eventName) {
- return new Promise((resolve, reject) => {
- let f = (event) => {
- element.removeEventListener(eventName, f)
- resolve(event)
- }
- element.addEventListener(eventName, f)
- })
- }
- async function PedestrianTrafficLight(parent, greenDelay, redDelay, redDelay2 = 1200) {
- while (true) {
- colorChange(parent, "green", 1)
- await delay(greenDelay)
- colorChange(parent, "red", 0)
- await Promise.race([delay(redDelay), domEventPromise(btn, 'click')]).then(async function () { await delay(redDelay2) })
- }
- }
- elemCreator(pedestrianLight, "div", 2);
- PedestrianTrafficLight(pedestrianLight, 6000, 6000)
- btn.addEventListener("click", changeButtonState)
- async function changeButtonState() {
- btn.disabled = true;
- await delay(10000)
- btn.disabled = false;
- }
- async function speedtest(getPromise, count, parallel = 1) {
- let t0 = performance.now();
- for (let i = 0; i < count; i++) {
- let promises = [];
- for (let j = 0; j < parallel; j++) {
- let res = getPromise();
- promises.push(res);
- }
- await Promise.all(promises)
- }
- let t1 = performance.now();
- let duration = t1 - t0;
- let querySpeed = count / duration;
- let queryDuration = duration / count;
- let parallelSpeed = (count * parallel) / duration;
- let parallelDuration = duration / (count * parallel);
- return {
- duration,
- querySpeed,
- queryDuration,
- parallelSpeed,
- parallelDuration
- }
- }
- speedtest(() => delay(1000), 10, 10).then(result => console.log(result))
- speedtest(() => fetch('http://swapi.dev/api/people/1').then(res => res.json()), 10, 5)
|