Why do different network browsers display different data for this piece of code?

<html> <head><title>Frontpage</title></head> <h3>Hello</h3> <script> var a=1; function myFunc(){ document.write(a+" "); a=a+1; myFunc(); } </script> <body><button type="button" onclick="myFunc()">Hey there</button></body> </html> 

The output file is from 0 to 53075 in Internet Explorer, while it is 12561 in Chrome. I donโ€™t understand why different browsers display different outputs and how it stops recursion. Thanks.

+5
source share
2 answers

This is a recursive function, and IE and Chrome have different Javascript rendering mechanisms. (Chrome uses V8). Most likely, these are a few inconsequential details about the internal components of a particular engine. In this case, it refers to the size of the stack (how many times something can be recursively called before it "explodes").

Another thing to think about is that for regular programs itโ€™s not so often to enter the call stack unless you think or do it on purpose, as your example above.

When I say "deep", I mean the fact that the evaluated operator (your function) should return a value, and if it does not (and instead calls another nested function), it should evaluate that the first. So it goes deeper. In your example, it will never be able to get the return value of anything until the free space runs out, because the innermost function never returns anything.

Here is another example:

 add(1, add(5, add(10, 20))) 

In this pseudo-code example, the add function takes 2 arguments, adds 2 numbers. The second argument must first be evaluated before it can get the return value (so that it can add it to 1). So ... it "pauses" the execution of 1 + ... , and then runs the second add function, which does the same. Now you have 2 functions that are 1 + ... , basically awaiting "hold". Finally, the innermost function returns 30 , so it gets 5 + 30 , which is 35, and now 35 goes to the remaining 1 + ... function to complete the calculation.

You might think that the depth of the stack is 3 (simple).

Basically, in your program, it does not get this final return value (to then pass the chain of calls). Instead, he simply leaves space and dies. Therefore, you simply check the limits of the various javascript engines and when they prefer to die.

+4
source

Well, this code is an infinite loop.

You should receive this type of message:

RangeError: Maximum call stack size exceeded.

Each browser has its own maximum number to allow this type of executable code. I really donโ€™t know, but run twice, and I got the same number, which means that this case is strictly forbidden with some maximum value.

+1
source

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


All Articles