繁体   English   中英

检测异步递归的结束

[英]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);
        }
    }

我在这里所做的是,我正在动态生成图片以填充16个画布,并且有人说我正在使用异步递归,而我什至没有注意到。 我试图使用循环而不是递归,但是以某种方式最终导致了我不知道如何解决的异常。 所以我坚持递归。 但是,我的问题是,如何像注释行一样检测到递归的结束,表明数组中只有一项。

//console.log(checkduplicates)

我得到的解释是,据我了解,注释的console.log是在一堆drawOne函数的递归完成之前执行的,但是我想要的是我希望完整加载全部16张图像,然后选择它们,以便我可以对他们做点什么。 因此,问题是如何检测递归结束。 谢谢。 欢迎您忽略我的大多数代码,而只看一下递归部分。

这不是“异步递归”。 这意味着这些循环中至少有两个同时运行,并且它们异步返回。 事实并非如此。

基本上,只有当i == canvaslength时,您才停止递归。

因此,只要使用if语句即可。

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM