-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy path5_callback_1.html
More file actions
104 lines (70 loc) · 2.68 KB
/
5_callback_1.html
File metadata and controls
104 lines (70 loc) · 2.68 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
</head>
<body>
<script>
// 자바스크립트는 동기적이다.
// hoisting이 된 후로 순서대로 코드가 작동한다.
// -> hoisting : var, function 등이 런타임시 제일 처음에서 실행되는것.
console.log('1');
console.log('2');
console.log('3');
// 그래서 위의 코드가 콘솔창에
// 1
// 2
// 3
// 이렇게 보인다.
console.log('---------------------------------');
// setTimeout(); 안에 콜백함수를 사용해보자
// setTimeout( function(){}, 밀리세컨드 );
// function(){}은 콜백함수로 사용되는데, 1000 = 1s 뒤 console.log('2');가 실행된다.
// 이렇게 실행되는것을 비동기적이라고 부른다.
console.log('1');
setTimeout( function() {
console.log('2');
},1000 );
console.log('3');
// 그래서 위의 코드가 콘솔창에
// 1
// 3
// 2
// 이렇게 보인다.
console.log('---------------------------------');
// 그럼 callback이 무조건 비동기식으로만 사용되는가?
// -> 아니다, callback은 동기, 비동기 모두 사용된다.
console.log('---------------------------------');
console.log('1');
setTimeout( function() {
console.log('2');
},1000 );
console.log('3');
// 동기식 callback
function printImmediately( print ) {
print();
}
printImmediately( ()=>console.log('hi') );
// 콘솔 결과
// 1
// 3
// hi
// 2
// 왜냐면 호이스팅으로 function이 해석순서 제일 위로올라오며,
// 그 뒤로 순차적으로 1,3이 해석되고, 그 다음에있는 printImmediately(); 가 실행된다.
// 그러고 setTimeout()이 어딘가에서 1초 대기하다가 보여진다.
// 이렇게
function printImmediately( print ) {
print();
}
console.log('1');
console.log('3');
printImmediately( ()=>console.log('hi') );
setTimeout( function() {console.log('2'); },1000 ); // 어딘가에서 1초동안 대기중
console.log('---------------------------------');
</script>
</body>
</html>