ํ‹ฐ์Šคํ† ๋ฆฌ ๋ทฐ

๊ณต๋ถ€/JS

[JS] Prevent Stack Overflow

Carrot๐Ÿฅ• 2020. 8. 6. 05:53

Exercise: Fix This Code

//fill array with 60000 elements
const list = new Array(60000).join('1.1').split('.');

function removeItemsFromList() {
    var item = list.pop();

    if (item) {
        removeItemsFromList();
    }
};

removeItemsFromList();

์œ„์˜ recursive function ์€ stack overflow ๋ฅผ ๋ฐœ์ƒ์‹œํ‚จ๋‹ค.

recursive call around ๋Š” ์œ ์ง€ํ•˜๋ฉด์„œ stack overflow ๋ฅผ ํ”ผํ•˜๋ ค๋ฉด ์–ด๋–ป๊ฒŒ ๊ณ ์ณ์•ผํ• ๊นŒ?

 


Solution Code

const list = new Array(60000).join('1.1').split('.');

function removeItemsFromList() {
    var item = list.pop();

    if (item) {
      setTimeout(removeItemsFromList, 0);
    }
};

removeItemsFromList();

 

 

๐Ÿ”ฝ ๋ฌธ์ œ ์ฝ”๋“œ ์‹คํ–‰ ์‹œ, ํฌ๋กฌ ๋ธŒ๋ผ์šฐ์ €์—์„œ ์Šคํƒ์˜ค๋ฒ„ํ”Œ๋กœ ๋ฐœ์ƒ 

 

๐Ÿ”ฝ ์†”๋ฃจ์…˜ ์ฝ”๋“œ ์‹คํ–‰ ์‹œ, ์ •์ƒ์ ์œผ๋กœ ๋ชจ๋“  ์ž‘์—… ๋งˆ์นจ

setTimeout ์— ์˜ํ•ด ๊ณผ์ •์ด ๋๋‚œ ๋’ค ์ฝœ๋ฐฑํ•จ์ˆ˜ ์‹คํ–‰ํ–ˆ๊ธฐ๋•Œ๋ฌธ!!!

 

 

์†”๋ฃจ์…˜_์ฝ”๋“œ_์‹คํ–‰๋˜๋Š”_๊ณผ์ •.gif๐Ÿ˜ฒ๐Ÿ˜ฒ๐Ÿ˜ฒ

(ํ•ด๋‹น ์ด๋ฏธ์ง€๋Š” http://latentflip.com/loupe ์ด์šฉํ•ด์„œ ๋งŒ๋“ค์—ˆ๊ณ ,
์ดํ•ด๋ฅผ ์œ„ํ•ด setTimeout ์˜ delay ๋ฅผ ์ถ”๊ฐ€ํ–ˆ์Šต๋‹ˆ๋‹ค!)

 

๋ฌธ์ œ ์ถœ์ฒ˜ : Udemy - JavaScript: The Advanced Concept 
https://www.udemy.com/course/advanced-javascript-concepts 

๋Œ“๊ธ€