๊ด€๋ฆฌ ๋ฉ”๋‰ด

C-log

JS์˜ ํ•ต์‹ฌ! ์ฝœ๋ฐฑ ํ•จ์ˆ˜ ๋ณธ๋ฌธ

๐Ÿ“’JS/โšกver.1

JS์˜ ํ•ต์‹ฌ! ์ฝœ๋ฐฑ ํ•จ์ˆ˜

4:Bee 2023. 5. 10. 17:31
728x90

 YouTube Link
 
์ž๋ฐ”์Šคํฌ๋ฆฝํŠธ 11. ๋น„๋™๊ธฐ ์ฒ˜๋ฆฌ์˜ ์‹œ์ž‘ ์ฝœ๋ฐฑ ์ดํ•ดํ•˜๊ธฐ, ์ฝœ๋ฐฑ ์ง€์˜ฅ ์ฒดํ—˜ ๐Ÿ˜ฑ JavaScript Callback | ํ”„๋ก ํŠธ์—”๋“œ ๊ฐœ๋ฐœ์ž ์ž…๋ฌธํŽธ (JavaScript ES6)
https://youtu.be/s1vpVCrT8f4

์šฐ์„  ์ฝœ๋ฐฑํ•จ์ˆ˜์˜ ์˜ˆ์‹œ ์ฝ”๋“œ๋“ค์„ ๋ณด์ž

function printImmediately(print) {
  print();
}

printImmediately(() => { console.log('hello') });

์œ„์˜ ์ฝ”๋“œ๋Š” ๋™๊ธฐ์‹ ์ฝœ๋ฐฑํ•จ์ˆ˜๋‹ค. ๋ง ๊ทธ๋ž˜๋„ ์ฝœ์„ ํ•œ ํ›„์— ์‹คํ–‰๋˜๋Š” ๊ฒƒ, ๊ทธ๊ฒƒ์ด ์ฝœ๋ฐฑํ•จ์ˆ˜์ด๋‹ค. printImmediately(() => { console.log('hello') }); ๋ฅผ ๋ณด๋ฉด () => { console.log('hello') ์ด ๋ถ€๋ถ„์ด ์ฝœ๋ฐฑ์ด ๋˜๋Š” ํ•จ์ˆ˜์ด๋‹ค. ์•„๋ž˜๋Š” ๋น„๋™๊ธฐ์‹ ์ฝœ๋ฐฑํ•จ์ˆ˜์ด๋‹ค.

function printWithDelay(print, timeout) {
  setTimeout(print, timeout);
}
printWithDelay(() => console.log('async callback'), 2000);

์—ฌ๊ธฐ์„œ ์šฐ๋ฆฌ๊ฐ€ ์ฝœ๋ฐฑํ•จ์ˆ˜๋ฅผ ์ œ์™ธํ•˜๊ณ  ์ฃผ๋ชฉํ•ด์•ผํ•˜๋Š” ๋˜๋‹ค๋ฅธ ๋ถ€๋ถ„์ด ์žˆ๋‹ค. ๊ทธ๊ฒƒ์€ ๋ฐ”๋กœ ๋งค๊ฐœ๋ณ€์ˆ˜์ด๋‹ค. ๋‹ค๋ฅธ ์–ธ์–ด๋ฅผ ์ ‘ํ•ด๋ณธ ์‚ฌ๋žŒ๋“ค์€ function printImmediately(print)์—์„œ print์ธ ๋งค๊ฐœ๋ณ€์ˆ˜๊ฐ€ print()ํ•จ์ˆ˜๋กœ ์ •์˜๋˜์–ด ์žˆ๋‹ค๋Š” ๊ฒƒ์ด ์กฐ๊ธˆ์€ ๋‹นํ™ฉ์Šค๋Ÿฌ์šธ ๊ฒƒ์ด๋‹ค. ๋ณดํ†ต ํƒ€์ž…์„ ์ž‘์„ฑํ•˜๊ณ  ๊ทธ์— ๋งž๋Š” ํƒ€์ž…์„ ๋Œ€์ž…ํ•˜์ง€๋งŒ Js์˜ ํŠน์ง•์ธ ์ž์œ ์„ฑ๋•Œ๋ฌธ์— ์ด๋Ÿฌํ•œ ์ฝ”๋“œ๊ฐ€ ๊ฐ€๋Šฅํ•˜๋‹ค. ํ•˜์ง€๋งŒ ์กฐ๊ธˆ๋งŒ ๋” ์ƒ๊ฐํ•ด๋ณด๋ฉด ๊ผญ ๊ทธ๋ ‡๊ฒŒ ์ด์งˆ์ ์ด์ง€๋งŒ์€ ์•Š๋‹ค. ๊ทœ์น™์„ ๋”ฐ๋ผ print๊ฐ€ ๋ฐ›์•„์•ผํ•  ๊ฒƒ์€ ๋ฐ”๋กœ ํ•จ์ˆ˜์ด๋ฏ€๋กœ print๋Š” print()๋ฅผ ์ฐธ์กฐํ•˜๊ณ  ์ด๋Š” ๊ณง () => { console.log('hello') } ์„ ์˜๋ฏธํ•œ๋‹ค. ๋ฌผ๋ก  ๋งค๊ฐœ๋ณ€์ˆ˜๋ช…์ด print๊ฐ€ ์•„๋‹Œ a์—ฌ๋„ print()ํ•จ์ˆ˜๋ฅผ ์ฐธ์กฐํ•œ๋‹ค. ๊ทธ๋ ‡๋‹ค๋ฉด ๋งค๊ฐœ๋ณ€์ˆ˜๊ฐ€ 2๊ฐœ์ธ ๊ฒฝ์šฐ๋Š” ์–ด๋– ํ• ๊นŒ.

function printImmediately(print) {
  print();
  scan();
}

printImmediately(() => { console.log('hello'), scan() });

 Js๊ฐ€ ์ฝ”๋“œ๋ฅผ ์ˆœ์ฐจ์ ์œผ๋กœ ํŒŒ์‹ฑ์„ ํ•˜๋ฉด์„œ ์šฐ์„  ์ˆœ์œ„์ธ print()ํ•จ์ˆ˜๋ฅผ ์ฐธ์กฐํ•œ๋‹ค. ๊ทธ๋ฆฌ๊ณ  scan()์€ ๋‹ค๋ฅธ scan()์ด๋ผ ์ •์˜๋˜์–ด ์žˆ๋Š” ํ•จ์ˆ˜๋ฅผ ์ฐธ์กฐํ•œ๋Š ๊ฒƒ์ด๋‹ค. 

function printImmediately(print, scan) {
  print();
  scan();
}

printImmediately(() => { console.log('hello') },() => { console.log('hello')});

์ด๋Š” ๋‹น์—ฐํžˆ print ๋งค๊ฐœ๋ณ€์ˆ˜๋Š” print()๋ฅผ ์ฐธ์กฐํ•˜๊ณ  scan๋งค๊ฐœ๋ณ€์ˆ˜๋Š” scan()์„ ์ฐธ์กฐํ•œ๋‹ค.


์ฝœ๋ฐฑํ•จ์ˆ˜๋Š” ํฌ๊ฒŒ ์–ด๋ ค์›€์ด ์—†์—ˆ๋Š๋‚˜ setTimout๊ณผ ๊ฐ™์€ ํ•จ์ˆ˜๋ฅผ ์‚ฌ์šฉํ•  ๋•Œ ์ฝœ๋ฐฑํ•จ์ˆ˜ํ˜•ํƒœ์˜ ๊ตฌ์กฐ๋ฅผ ๊ฐ€์ง€๊ณ  ์žˆ๋‹ค๋Š” ๊ฒƒ์„ ์ƒ๊ฐํ•˜๋ฉด์„œ ์ฝ”๋“œ๋ฅผ ์ž‘์„ฑํ•˜๋ฉด ์ข‹๋‹ค.

728x90
Comments