Stack Overflow caused by deep recursion in Javascript, the ultimate solution

Source: Internet
Author: User
<SCRIPT> var I = 0; function callback () {I ++; document. writeln (I); if (I = 1000000000) {return; // It is returned after many times. in IE, a stack overflow occurs in more than 3000 layers, and Google browsers are larger than 1.1 to 9500 ..} else {callback (); // recursive call} callback (I); </SCRIPT>

The above sectionCodeIn IE and Google, Firefox will cause stack overflow, but not all operations.

Change it to the following one ..

<SCRIPT> var I = 0; function callback (P1, P2, P3, P4) {I ++; document. writeln (P1); if (I = 100000) {return; // It is returned after many times. in IE, a stack overflow occurs in more than 3000 layers, and Google browsers are larger than 1.1 to 9500 ..} else {addtask (callback, 0, "parameter" + I, "parameter 2", "parameter 3", "parameter 4 "); // recursive call becomes a non-recursive call}/*** to add a task, * @ Param {function} fun task function name * @ Param {number} delay scheduled time * @ Param {object} Params parameter passed to Fun */function addtask (fun, delay) {If (typeof fun = 'function') {var argu = array. prototype. slice. call (arguments, 2); var F = (function () {fun. apply (null, argu) ;}); return window. setTimeout (F, delay);} return window. setTimeout (fun, delay);} callback (I); </SCRIPT>

 

Cleverly utilizes window. setTimeout to implement recursive interruption.

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.