I have a question about asynchrony in JS. How it actually works. I'm not sure if I got it right, I hope you can help me figure it out.
So, I have a code:
console.log('start');
setTimeout(() => console.log('one'), 0);
console.log('two');
setTimeout(() => console.log('three'), 3000);
console.log('finish');
- So
console.log('start')
gets into the CallStack, executes and ride out of it. In the console, I get the output 'start'. - Next,
setTimeout(() => console.log('one'), 0)
gets into CallStack, but since this is an asynchronous function from CallStack, it goes to the Web API and works there in the background. As soon as it completes, its callback function will ‘move’ to the Callback queue. - Then
console.log('two')
also gets into the CallStack, is executed and removed. In the output now we have (‘start’, ‘two’) - Exactly the same story happens with
setTimeout(() => console.log('three'), 3000);
- Again we repeat the same actions with
console.log('finish')
and in the output we have (‘start’, ’two’,’finish’) - It turns out that the Callback queue contains (‘one’, ’three’).
- From the Callback queue
console.log('one')
gets into the Call Stack, is executed and deleted. The output is (‘start’,’two’, ’finish’, ’one'), etc.
It turns out that event loop checks if the CallStack is empty, if it is empty and the Callback queue contains a callback function, then it pushes them into the CallStack and does it until the Callback queue is empty?