Skip to content

Instantly share code, notes, and snippets.

@davidsierradz
Created September 19, 2018 02:42
Show Gist options
  • Save davidsierradz/2c65d6a8a96e383ae37db07cbf1c3fcb to your computer and use it in GitHub Desktop.
Save davidsierradz/2c65d6a8a96e383ae37db07cbf1c3fcb to your computer and use it in GitHub Desktop.
A basic example showing how to run code over an array without blocking the event loop
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width" />
<title>Don't block the event loop</title>
</head>
<body>
<div id="root"></div>
<script>
const asyncLoop = (i, root, arr) => {
const element = document.createElement('div');
element.innerHTML = `<p>${arr[i]}</p>`;
root.appendChild(element);
if (i < arr.length - 1) {
setTimeout(() => {
asyncLoop(++i, root, arr);
}, 0);
}
};
document.addEventListener('DOMContentLoaded', () => {
const root = document.getElementById('root');
asyncLoop(0, root, [...Array(100).keys()]);
});
</script>
</body>
</html>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment