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