开发者

detect the end of asynchronous recursion

var checkduplicates = new Array();
drawOne(i); 
//console.log(checkduplicates)

function drawOne(i)
{
    //randomly select one photo
    var picinfo = photos[Math.floor(Math.random()*photos.length)];
    //check duplicates pic, if duplicates exist, get another one
    while(checkduplicates.indexOf(picinfo)!=-1||picinfo.title.length>10)
    {
        picinfo = photos[Math.floor(Math.random()*photos.length)];
    }
    checkduplicates.push(picinfo);

    var ctx = document.getElementsByClassName("canvas")[i].getContext('2d');
    var img = new Image(); 
    //get the pic URL
    img.src = "http://farm" + picinfo.farm + ".static.flickr.com/"
    + picinfo.server + "/" + picinfo.id + "_" + picinfo.secret + "_m.jpg";

    img.onload = function()
    {
        // Draw pieces
        ctx.drawImage(img,0,0,132,150);
        ctx.drawImage(frame,0,0,133,152);
        if(picinfo.title=="")
            $("#"+i).append("Untitled");
        else
            $("#"+i).append(picinfo.title);

        i++;
        if (i != canvaslength)
        {
            drawOne(i);
        }
    }

What I am doing here is that I am dynamically generate pictures to fill out 16 canvas and some people said that I am using asynchronous recursion which I dont even notice. I have tried to use loop instead of recursion but somehow ended it up getting exception that i dont know how to fix. So I stick to recursion. However, my problem is that how I can detect the end of the recursion like the commented line shows there is only one item in the array.

//console.log(checkduplicates)

and the explanation I got is that as I understand, the commented console.log is executed before a bunch of recursion of drawOn开发者_JS百科e function finished But what I wanted was that I wanted the full 16 images to be fully loaded and then select them so that I can do something with them. Therefore, the question is how I can detect the end of the recursion. Thank you. You are welcomed to ignore most of my codes and just look at the recursion part.


This is not 'asynchronous recursion'. That would imply that at least two of these loops are running at the same time, and they return asynchronously. Which is simply not the case.

Basically the only time you STOP recursion is when i == canvaslength.

So, just take that if statement.

if (i != canvaslength)
{
    drawOne(i);
}else{
    console.log('recursion is done')  // do what you want here.
}
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜