🌻 요청에 대한 결과가 동시에 일어나지 않는다 !
code
패턴을 작성할 수 있다.setTimeout
등의 비동기 호출 함수를 이용할 수 있다.argument
)로 넘겨주는 함수(B)parameter
를 넘겨받는 함수(A)는 callback
함수(B)를 필요에 따라 즉시 실행(synchronously
) 할수도 있고, 아니면 나중에 (asynchronously
) 실행할 수도 있다.function B() {
console.log('called at the back!');
}
function A(callback) {
callback(); // callback === B
}
A(B);
▶︎ callback in action : 반복 실행하는 함수 (iterator)
[1, 2, 3].map(function(element, index) {
return element * element;
}); -> 안쪽에 있는 `callback function`이 반복적으로 3번 실행된다.
▶︎ callback in action : 이벤트에 따른 함수 (event handler)
document.querySelector('#btn').addEventListener('click', function(e) {
console.log('button clicked');
});
▶︎ 함수 실행을 연결하는 것이 아니라, 함수 자체를 연결해야한다!
function handleClick() {
console.log('button clicked');
}
✔︎ document.querySelector('#btn').onclick = handleClick;
✔︎ document.querySelector('#btn').onclick = function() {
handleClick();
}
✔︎ document.querySelector('#btn').onclick = handleClick.bind();
❌ document.querySelector('#btn').onclick = handleClick();
-> 함수 실행을 연결하고 있으므로 잘못된 코드이다.
▶︎ 동기 : 요청에 대한 결과가 동시에 일어난다
function waitSync(ms) {
var start = Date.now();
var now = start;
while(now - start < ms) {
now = Date.now();
}
} // 현재 시각과 시작 시각을 비교하며 ms 범위 내에서 무한 루프를 도는 blocking 함수입니다
function drink(person, coffee) {
console.log(person + '는 ' + coffee + '를 마십니다');
}
function orderCoffeeSync(coffee) {
console.log(coffee + '가 접수되었습니다');
waitSync(2000);
return coffee;
}
let customers = [{
name: 'Steve',
request: '카페라떼'
}, {
name: 'John',
request: '아메리카노'
}];
// call synchronously
customers.forEach(function(customer) {
let coffee = orderCoffeeSync(customer.request);
drink(customer.name, coffee);
});
function waitAsync(callback, ms) {
setTimeout(callback, ms); // 특정 시간 이후에 callback 함수가 실행되게끔 하는 브라우저 내장 기능입니다
}
function drink(person, coffee) {
console.log(person + '는 ' + coffee + '를 마십니다');
}
function orderCoffeeSync(coffee) {
console.log(coffee + '가 접수되었습니다');
waitSync(2000);
return coffee;
}
let customers = [{
name: 'Steve',
request: '카페라떼'
}, {
name: 'John',
request: '아메리카노'
}];
function orderCoffeeAsync(menu, callback) {
console.log(menu + '가 접수되었습니다');
waitAsync(function() {
callback(menu);
}, 2000);
}
// call asynchronously
customers.forEach(function(customer) {
orderCoffeeAsync(customer.request, function(coffee) {
drink(customer.name, coffee);
});
});
click
, keydown
등)DOMContentLoaded
등)setTimeout
등)requestAnimationFrame
)fetch API
AJAX(XHR)