Skip to content

Commit 9a01936

Browse files
committed
Sync/Async: event loop on browser and runtime node.js
1 parent bcc9a8b commit 9a01936

File tree

1 file changed

+43
-0
lines changed

1 file changed

+43
-0
lines changed

Sync-Async/Event Loop/index.js

Lines changed: 43 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,43 @@
1+
// Example 1
2+
3+
// function one(x) {
4+
// x++;
5+
// setTimeout(() => {
6+
// console.log(`setTimeout ${x}`);
7+
// });
8+
// two(x);
9+
// }
10+
11+
// function two(y) {
12+
// y++;
13+
// three(y);
14+
// }
15+
16+
// function three(z) {
17+
// z++;
18+
// console.log(`This is the third func: ${z}`);
19+
// }
20+
21+
// one(1);
22+
23+
// Example 2
24+
const s = Date.now();
25+
26+
// C: a asynchronous code
27+
setTimeout(() => {
28+
console.log(`setTimeout 1st: ${Date.now() - s}`);
29+
}, 1000);
30+
31+
// D: another asynchronous code
32+
setTimeout(() => {
33+
console.log(`setTimeout 2nd: ${Date.now() - s}`);
34+
}, 3000);
35+
36+
// A: a synchronous code takes 3.5s
37+
let result = 0;
38+
for (let i = 0; i < 3000000000; i++) {
39+
result = result + i;
40+
}
41+
42+
// B: another synchronous code, will be blocked, and run after A
43+
console.log(`Sync: ${result} - ${Date.now() - s}`);

0 commit comments

Comments
 (0)