๐ก ์ฝ๋ฐฑ (Callback)
ํจ์์ ์ธ์๋ก ์ฌ์ฉ๋๋ ํจ์
์๋ฅผ๋ค์ด
setTimeout(ํจ์, ์๊ฐ)์์
setTimeout์ ์ธ์๋ก ์ฌ์ฉ๋ ํจ์๋ฅผ ์ฝ๋ฐฑ์ด๋ผ๊ณ ๋ถ๋ฅธ๋ค.
function timeout() {
setTimeout(() => {
console.log('3์ด๋ค๋์จ๋ค');
}, 3000)
}
timeout();
console.log('๋');

Q : ์ฌ๊ธฐ์ '๋'์ '3์ด๋ค๋์จ๋ค'๋ค์ ๋์ค๊ฒ ํด์ฃผ๋ ค๋ฉด ์ด๋ป๊ฒ ํด์ผํ ๊น?
function timeout() {
setTimeout(() => {
console.log('3์ด๋ค๋์จ๋ค');
console.log('๋');
}, 3000)
}
timeout();
๋ : ์ด๋ ๊ฒ ํ๋ฉด ๋๋๊ฑฐ ์๋?ใ ๊ฐ์ฒ์ฌ
Q :
ใ
timeoutํจ์๋ฅผ
ใ
๊ฑด๋ค๊ธฐ์ซ์ผ๋ฉด์?
๋ : ๋์ฒด ์ ๊ทธ๋ฐ ์๊ฐ์ ํด์ผํ๋๋ฐ..?๐
์ ๋ตโฌ
function timeout(callback) {
setTimeout(() => {
console.log('3์ด๋ค๋์จ๋ค');
callback();
}, 3000)
}
timeout(() => {
console.log('๋');
});
timeout(() => {
console.log('๋');
});
timeoutํจ์๋ฅผ ํธ์ถํ ๋ ํ๋์ ์ต๋ช
ํจ์๋ฅผ ์ธ์๋ก ์ฌ์ฉ.
๊ทธ ์ธ์ console.log('๋');๋ (callback)์ด๋ผ๋ ๋งค๊ฐ๋ณ์๋ก ๋ค์ด๊ฐ๋ค.
์ด์ (callback)์ ํ๋์ ํธ์ถ๋์ง ์์ ํจ์.
๊ทธ ํจ์๋ฅผ ๋ด๊ฐ ํธ์ถํ๊ณ ์ถ์ ์๋ฆฌ์ ํธ์ถํด์ค๋ค.
function timeout(callback) {
setTimeout(() => {
console.log('3์ด๋ค๋์จ๋ค');
callback();
}, 3000)
}
๐ก callback์ ์คํ์์น๋ฅผ ๋ณด์ฅํ๋ ์ฉ๋๋ก ๋ง์ด ํ์ฉ๋๋ค!