1const first = () => console.log('Hi,i am first');
2const second = () => console.log('Hi,i am second');
3const third = () => console.log('Hi,i am third');
4const fourth = () => {
5 first();
6 setTimeout(second, 4000);
7 //store in queue & it will execute after 4 seconds
8 setTimeout(third, 2000);
9 //store in queue & it will execute after 2 seconds
10 console.log('Hi,i am fourth');
11};
12fourth();
13
14//Expected output:
15/*Hi,i am first
16 Hi,i am fourth
17 Hi,i am third
18 Hi,i am second
19*/
1The Event Loop has one simple job — to monitor the Call Stack
2and the Callback Queue. If the Call Stack is empty, it will
3take the first event from the queue and will push it to the
4Call Stack, which effectively runs it. Such an iteration is
5called a tick in the Event Loop. Each event is just a function
6callback.
7
8#bpn
1
2
3
4
5 console.log('Hi!');
6
7setTimeout(() => {
8 console.log('Execute immediately.');
9}, 0);
10
11console.log('Bye!');
12Code language: JavaScript (javascript)
1The Event Loop has one simple job — to monitor the Call Stack
2and the Callback Queue
1 function task(message) {
2 // emulate time consuming task
3 let n = 10000000000;
4 while (n > 0){
5 n--;
6 }
7 console.log(message);
8}
9
10console.log('Start script...');
11task('Download a file.');
12console.log('Done!');
13Code language: JavaScript (javascript)
1console.log('Hi!');
2
3setTimeout(() => {
4 console.log('Execute immediately.');
5}, 0);
6
7console.log('Bye!');
8
9// print order
10// 'Hi!'
11// 'Bye!'
12// 'Execute immediately.'