Created
September 19, 2018 02:42
-
-
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
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<!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