Last active
December 15, 2016 10:21
-
-
Save eiszfuchs/53b1441cf91ee5b0060394ef461b0344 to your computer and use it in GitHub Desktop.
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"> | |
<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