Skip to content

Instantly share code, notes, and snippets.

@domfarolino
Created November 28, 2016 16:20
Show Gist options
  • Save domfarolino/d9f0b0d56c1785842552ca250ea385ad to your computer and use it in GitHub Desktop.
Save domfarolino/d9f0b0d56c1785842552ca250ea385ad to your computer and use it in GitHub Desktop.
Demonstrating how asynchronous code can let the browser render the UI in between propagated async callbacks
const array = [1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1];
function handleArrayValue(v) {
console.log(`Handling ${v}`);
for (let i = 0; i < 15000; ++i) {
for (let j = 0; j < i; ++j) {
// Nothing!
}
}
}
function asyncForEach(cb) {
this.forEach(v => {
setTimeout(_ => {
cb(v);
}, 0);
});
}
Array.prototype.asyncForEach = asyncForEach;
document.querySelector('#asyncTrigger').addEventListener('click', evt => {
array.asyncForEach(handleArrayValue);
});
document.querySelector('#syncTrigger').addEventListener('click', evt => {
array.forEach(handleArrayValue);
});
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>Async For Each</title>
<link rel="stylesheet" href="master.css">
<link href="https://fonts.googleapis.com/icon?family=Roboto" rel="stylesheet">
</head>
<body>
<h1>UI Render Blocking Example</h1>
<div id="expander"></div>
<div id="lorem">
<button id="syncTrigger" type="button" name="button">Synchronous <code>.forEach(...)</code></button>
<button id="asyncTrigger" type="button" name="button">Asynchronous <code>.forEach(...)</code></button>
<p style="margin-top: 10px">
"Sed ut perspiciatis unde omnis iste natus error sit voluptatem accusantium doloremque laudantium,
totam rem aperiam, eaque ipsa quae ab illo inventore veritatis et quasi architecto beatae vitae dicta
sunt explicabo. Nemo enim ipsam voluptatem quia voluptas sit aspernatur aut odit aut fugit, sed quia
consequuntur magni dolores eos qui ratione voluptatem sequi nesciunt. Neque porro quisquam est, qui
dolorem ipsum quia dolor sit amet, consectetur, adipisci velit, sed quia non numquam eius modi tempora
incidunt ut labore et dolore magnam aliquam quaerat voluptatem. Ut enim ad minima veniam, quis nostrum
exercitationem ullam corporis suscipit laboriosam, nisi ut aliquid ex ea commodi consequatur? Quis autem
vel eum iure reprehenderit qui in ea voluptate velit esse quam nihil molestiae consequatur, vel illum qui
dolorem eum fugiat quo voluptas nulla pariatur?"
</p>
</div>
<script src="asyncForEach.js" defer></script>
</body>
</html>
* {
margin: 0;
padding: 0;
box-sizing: border-box;
font-family: Roboto, sans-serif;
}
h1 {
text-align: center;
}
#expander {
background: firebrick;
width: 200px;
height: 200px;
margin: 80px auto;
transition: transform 2s;
}
#expander:hover {
transform: rotate(180deg);
}
#lorem {
width:90%;
max-width: 500px;
margin: 0 auto
}
button {
padding: 10px;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment