I'm learning execution stack, task queue and event loop mechanism.
I continuously clicked the button until main thread is available (just before function a() is done) like below.
I thought click(UI) events and setTimeout uses the same queue, called Macrotask or Task Queue, so when I click the button between 1s and 3s, I thought the log of the task2 is printed between task1 and task2. But the result was not like that. Task2(click event) is always printed first and setTimeout events(task1,task3) are printed after click events.
So I'm wondering if click events are using different queue mechanism from setTimeout, or click event is prioritized over setTimeout.
thank you in advance for your help
Operation
- click the button (task2)
- --------1000ms setTimeout task1--------
- click the button (task2)
- --------3000ms setTimeout task3--------
- click the button (task2)
- --------6000ms main thread is now available--------
My Expectation Log Order
fn a done
task2 (click) done
task1 (setTimeout 1000ms) done
task2 (click) done
task3 (setTimeout 3000ms) done
task2 (click) done
Result Log Order
fn a done
task2 (click) done
task2 (click) done
task2 (click) done
task1 (setTimeout 1000ms) done
task3 (setTimeout 3000ms) done
Code
const btn = document.querySelector('button');
btn.addEventListener('click', function task2() {
console.log('task2 (click) done');
});
function a() {
setTimeout(function task1() {
console.log('task1 (setTimeout 1000ms) done');
}, 1000);
setTimeout(function task3() {
console.log('task3 (setTimeout 3000ms) done');
}, 3000);
// hold main thread for 6000ms(*1)
const startTime = new Date();
while (new Date() - startTime < 6000);
console.log('fn a done');
}
a();
<button>button</button>
<script src="main.js"></script>