const delay = ms => new Promise(ok => setTimeout(() => ok(ms), ms)) let div = document.createElement('div') document.body.append(div) //domEventPromise let btn = document.createElement('button') btn.innerText = 'click' document.body.append(btn) function domEventPromise(elem, eventName) { let prom = new Promise((resolve, reject) => { function doAndRemove(event) { elem.removeEventListener(eventName, doAndRemove) resolve(event) } elem.addEventListener(eventName, doAndRemove) }) return prom } domEventPromise(btn, 'click').then((event) => console.log('event click happens', event)) async function pedestrianTrafficLight(parent, redTime = 4000, yellowTime = 2000, greenTime = 2000) { let container = document.createElement('div') container.style.backgroundColor = 'grey' container.style.width = 'fit-content' container.style.padding = '5px' let btn = document.createElement('button') btn.innerText = 'pedestrian button' let colors = [] for(let i = 0; i < 3; i++) { let color = document.createElement('div') color.style.backgroundColor = 'black' color.style.width = '100px' color.style.height = '100px' color.style.borderRadius = '100%' color.style.margin = '10px' container.append(color) colors.push(color) } container.append(btn) parent.append(container) while (true) { let pressed = false btn.disabled = false switch ('red') { case 'red': colors[0].style.backgroundColor = 'red' colors[0].style.boxShadow = '0px 2px 10px red' await Promise.race([delay(redTime), domEventPromise(btn, 'click')]).then((e) => { if (typeof e === 'object') { pressed = true } }) colors[0].style.boxShadow = 'none' colors[0].style.backgroundColor = 'black' case 'yellow': if (pressed === true) break; colors[1].style.backgroundColor = 'yellow' colors[1].style.boxShadow = '0px 2px 10px yellow' await Promise.race([delay(yellowTime), domEventPromise(btn, 'click')]).then((e) => { if (typeof e === 'object') { pressed = true } }) colors[1].style.boxShadow = 'none' colors[1].style.backgroundColor = 'black' } colors[2].style.backgroundColor = 'lightgreen' colors[2].style.boxShadow = '0px 2px 10px lightgreen' btn.disabled = true await delay(greenTime) colors[2].style.boxShadow = 'none' colors[2].style.backgroundColor = 'black' } } pedestrianTrafficLight(div, 3000, 3000, 3000) // speedtest async function speedtest(getPromise, count,parallel=1){ let _parallel = parallel let duration = performance.now() for(let i = 0; i < count; i++) { let promises = [] while(parallel !== 0) { promises.push(await getPromise()) parallel -= 1 } Promise.all(promises) } duration = performance.now() - duration return { duration: duration, querySpeed: 1 / (duration / count), queryDuration: duration / count, parallelSpeed: (count * _parallel) / (duration / count), parallelDuration: duration / (count * _parallel) } } //speedtest(() => delay(1000), 10, 10 ).then(result => console.log('result',result)) speedtest(() => fetch('http://swapi.dev/api/people/1').then(res => res.json()), 10, 5).then(result => console.log('result',result))