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*/
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.'