Skip to content

Instantly share code, notes, and snippets.

@IvanRave
Created April 16, 2019 14:10
Show Gist options
  • Save IvanRave/69a652af47a47f088191f18aa7ce87e9 to your computer and use it in GitHub Desktop.
Save IvanRave/69a652af47a47f088191f18aa7ce87e9 to your computer and use it in GitHub Desktop.
JS Bin // source https://jsbin.com/kuzitob
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width">
<title>Tasks and microtasks / Javascript event loop</title>
</head>
<body>
<button id="btn">Click me</button>
<div id="output"></div>
<script id="jsbin-javascript">
const log = (msg) => {
output.innerHTML += `<div>${msg}</div>`;
};
btn.addEventListener('click', () => {
Promise.resolve().then(() => {
log('microtask 1');
Promise.resolve().then(() => {
log('microtask 1.1');
})
});
setTimeout(() => log('task 1'), 0);
log('click 1');
})
btn.addEventListener('click', () => {
Promise.resolve().then(() => log('microtask 2'));
setTimeout(() => log('task 2'), 0);
log('click 2');
})
btn.click();
log('initial stack is empty');
</script>
<script id="jsbin-source-javascript" type="text/javascript">const log = (msg) => {
output.innerHTML += `<div>${msg}</div>`;
};
btn.addEventListener('click', () => {
Promise.resolve().then(() => {
log('microtask 1');
Promise.resolve().then(() => {
log('microtask 1.1');
})
});
setTimeout(() => log('task 1'), 0);
log('click 1');
})
btn.addEventListener('click', () => {
Promise.resolve().then(() => log('microtask 2'));
setTimeout(() => log('task 2'), 0);
log('click 2');
})
btn.click();
log('initial stack is empty');</script></body>
</html>
const log = (msg) => {
output.innerHTML += `<div>${msg}</div>`;
};
btn.addEventListener('click', () => {
Promise.resolve().then(() => {
log('microtask 1');
Promise.resolve().then(() => {
log('microtask 1.1');
})
});
setTimeout(() => log('task 1'), 0);
log('click 1');
})
btn.addEventListener('click', () => {
Promise.resolve().then(() => log('microtask 2'));
setTimeout(() => log('task 2'), 0);
log('click 2');
})
btn.click();
log('initial stack is empty');
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment