JS SetTimeout completion callback after depth recursion

Source: Internet
Author: User

Settimout Prototypes:

Itimerid = Window.settimeout (Vcode, Imilliseconds [, Slanguage])

There are two forms of settimeout

SetTimeout (Code,interval)
SetTimeout (Func,interval,args)

var i=0;
function Test () {
I+=1;
alert (i);
}
SetTimeout ("Test ()", 1000);
You can also do this:
SetTimeout (test,1000);

Problem:

Because recursion is too deep to use the asynchronous SetTimeout Clean air-conditioning stack, the entire recursion becomes the asynchronous behavior, the function has been returned in advance, now how to set the entire recursive completion of the callback?

Reply:

//No callbacks functionIsArray (o) {returnTostring.apply (o) = = = ' [Object Array] '; } functionfoo (arr) {console.log (arr); if(IsArray (arr)) { for(Iincharr) {             (function(j) {SetTimeout (function() {foo (arr[j]); }, 0);         }) (i); }}} foo ([[1, 2], [3, 4]]);

/*
Output:
[[1,2],[3,4]]
[Up]
[3,4]
1
2
3
4
*/

 //have callbacks functionIsArray (o) {returnTostring.apply (o) = = = ' [Object Array] '; } //set a counter that identifies "the number of elements known to have not been traversed", with a starting value of apparently 1 varCbcounter = 1; functionfoo (arr, CB) { Cbcounter + = IsArray (arr)? arr.length:0;//number of elements plus, because child elements are now knownConsole.log (arr); if(IsArray (arr)) { for(Iincharr) {             (function(j) {SetTimeout (function() {foo (arr[j], CB); }, 0);         }) (i); }     }     if((--cbcounter = = 0) && (typeofcb = = = ' function ')) CB ();//the one in front--is to dig yourself out.} foo ([[1, 2], [3, 4]],function() {Console.log (' I am a callback! '); }); 

/*
Output:
[[1,2],[3,4]]
[Up]
[3,4]
1
2
3
4
I am a callback!
*/

JS SetTimeout completion callback after depth recursion

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.