When does the browser stop performing a recursive function in javascript?

I am new to javascript. I tried a recursive function in javascript.

<html> <head> </head> <body> <script type = "text/javascript"> function first(){ document.write(" first"); first(); } first(); </script> </body> </html> 

The browser prints โ€œfirstโ€ for a finite number of times. Why is this? Is there any specific mechanism to stop printing โ€œfirstโ€ after a certain amount of time? Is it a specific browser?

+4
source share
3 answers

Recursive functions are not infinite - they can continue only until the stack space ends.

'Stack space' in this context is the memory that the program (i.e. the browser) allocates to remember the chain of function calls, so when your functions return, it knows where to return.

This memory space is limited, and when it ends, the program will stop and give an error (error).

If you are using a browser that has a developer tool window (i.e., almost all major browsers), you should see that the error is displayed in the console window when this happens.

The exact number of times the browser will run your loop depends on the browser and how much memory it has allocated for the stack. It is not that you have direct control - of course, not in the context of the browser; in lower-level programming, such as a C / C ++ program, you will have tools to determine the size of the stack yourself, but in the browser these things are uncontrollable. However, the browser should allocate enough memory for the stack so that the program will never hit it unless it falls into an infinite loop.

+4
source

Check this question JavaScript Infinite Loop? and use the code in the response to achieve the loop:

 window.onload = function start() { slide(); } function slide() { var num = 0, style = document.getElementById('container').style; window.setInterval(function () { // increase by num 1, reset to 0 at 4 num = (num + 1) % 4; // -600 * 1 = -600, -600 * 2 = -1200, etc style.marginLeft = (-600 * num) + "px"; }, 3000); // repeat forever, polling every 3 seconds } 
0
source

Recursive functions work in all languages. You must write a return statement that if the condition is true, return something else, call the function again. It all depends on the requirements of how you want to use them. It could be an algo.

 function func_name(){ if ( condition is true ) return something ... ... ... func_name() } 
0
source

Source: https://habr.com/ru/post/1443198/


All Articles