2. Loose event handling on large set
Same as earlier, but using promises.
Google Chrome 243.71000000000004 µ seconds
by Renoir Boulanger
HTML
<p>
Last clicked item is <code id="lastClicked">None</code>
</p>
<ul></ul>
CSS
div {opacity:0;transition: opacity 1s;}
div.show { opacity:1;}
JavaScript
let maxIter = 80000;
var t0 = window.performance.now();
function clickHandler(evtObj) {
let innerText = evtObj.target.innerText
, lastClicked = document.querySelector('#lastClicked') || 'None';
lastClicked.innerText = innerText;
/**
* Nothing fancy, just a notifier copy-pasta from MDN
* https://developer.mozilla.org/en-US/docs/Web/API/notification
**/
if (!!("Notification" in window)) {
if (Notification.permission !== 'denied') {
Notification.requestPermission(function (permission) {
// If the user accepts, let's create a notification
if (permission === "granted") {
var notification = new Notification(`Last clicked was ${innerText}`);
}
});
}
}
}
function createListElement(i, textTemplate=`Item `) {
let innerText = textTemplate + Number(i);
return `<li>${innerText}</li>`;
}
/** ============= Building things now ================= **/
let list = document.querySelector('ul')
, elements = Array(Number(maxIter)).fill('Foo ')
, out = '';
list.addEventListener("click", clickHandler, {}, true);
elements
.forEach( (str, idx) => {
out += createListElement(idx, str);
});
list.innerHTML = out;
/** ============ Performance timing ============ **/
var t1 = window.performance.now()
, calc = Number(t1) - Number(t0)
, calcText = `Took ${calc} seconds`
, calcFrag = document.createElement('p');
calcFrag.textContent = calcText;
document.querySelector('#lastClicked').parentNode.insertBefore(calcFrag, null);