Skip to content

Instantly share code, notes, and snippets.

@eiszfuchs
Last active December 15, 2016 10:21
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save eiszfuchs/53b1441cf91ee5b0060394ef461b0344 to your computer and use it in GitHub Desktop.
Save eiszfuchs/53b1441cf91ee5b0060394ef461b0344 to your computer and use it in GitHub Desktop.
<!doctype html>
<html>
<head>
<meta charset="utf-8">
<title>Asynchronous JavaScript???</title>
</head>
<body>
<output name="tick"></output>
<pre id="results"></pre>
<br>
<!-- https://google.com/search?q=asynchronous%20functions%20javascript -->
<button onclick="longTask();">Start long task</button>
<button onclick="longTaskTimeout();">Start long task with timeout</button>
<button onclick="longTaskPromise();">Start long task with Promise</button>
</body>
<script>
let tick = 0;
window.setInterval(() => {
tick += 1;
document.querySelector('[name="tick"]').textContent = tick;
}, 1000 / 20);
const noop = () => {};
const wait = (time = 2000) => {
const start = new Date();
let result = 0;
while ((new Date()) - start < time) {
result += 1;
}
return result;
}
const longTask = (done = noop) => {
document.querySelector('#results').textContent += `I counted to ${wait(2000)}!\n`;
done();
};
const longTaskTimeout = () => {
window.setTimeout(longTask, 0);
};
const longTaskPromise = () => {
new Promise((resolve, reject) => {
longTaskTimeout(resolve);
});
};
</script>
</html>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment