function B() {
console.log('called at the back!');
}
function A(callback) {
callback(); // callback === B
}
A(B);
[1,2,3].map(function(elem, index) {
return elem * index;
});
document.querySelector('#btn').addEventListener('click', function(e) {
console.log('button clicked');
})
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);
});
#### 비동기
```js
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);
});
});
비동기 처리 이해를 돕기위해 참고한 블로그
: https://joshua1988.github.io/web-development/javascript/javascript-asynchronous-operation/
https://developer.mozilla.org/ko/docs/Web/JavaScript/EventLoop
https://vimeo.com/96425312