Skip to content

Instantly share code, notes, and snippets.

@IvanRave
Created Apr 16, 2019
Embed
What would you like to do?
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