繁体   English   中英

Javascript:延迟在html5画布上循环绘制

[英]Javascript: Delay drawing on html5 canvas in a loop

我使用的代码生成树数据结构的图片。 如果调用了一个向树添加值的函数,它将搜索应附加新值的节点。 这是循环完成的。 如果找到正确的节点,它将添加该值。 每一步之后,该函数应在html5画布上绘制树,并以与树其余部分不同的颜色来显示当前选中的节点(如果是附加值的节点)。 要查看结果,在绘制一个步骤和下一个步骤之间应该有一个延迟。 如果我只是像这样执行代码,那么您看到的唯一就是最后一步,因为一切都发生得太快了。

(更具体地说,数据结构是一个trie树,增加的值是一个单词。每个节点都是一个字母。如果存在单词“ cat”,并且添加单词“ care”,则树会搜索根以查找c,搜索它找到a,搜索什么都没有找到,然后在a之后添加r,将r添加到r,并向e添加一个“单词结尾”节点。为每个可能的树循环。)

我不知道如何将setTimeout()放在那里。 我可以自己编写一个延迟函数,但是这样会使浏览器停止运行,直到完成延迟为止?

有谁知道我能做什么? 提前致谢。

编辑:这个伪的东西是添加功能现在所做的。 这不是实际的代码,而是完全一样。 抱歉,有点长...

Trie add function {

    get a word via prompt

    stop if word doesnt consist of only letters /* at least one letter */

    working node = trie root /* the node that Im currently checking */
    node color = bright color
    draw the tree
    node color = normal color

    for(every letter in word){

            if working node has no child nodes{
                make new node
                new node value = current letter
                new node parent = working node
                working node children = array consisting of new node
                working node = new node
            }
            else{ /* child nodes exist, search for current letter */
                found = false
                for(every child node of working node){
                    if(child node value === current letter){
                        working node = current child node of working node
                        found = true
                        break
                    }
                }

                /* if current letter doesnt exist */
                if(!found){
                    make new node
                    new node value = current letter
                    new node parent = working node
                    add new node to array of children of working node
                    working node = new node
                }   
            }

            // !!! there should be a delay before this happens !!!

            working node color = bright color
            draw the tree
            working node color = normal color
    }

    make new end node
    end node parent = working node
    add end node to children of working node
    working node = end node

    // !!! there should be a delay before this happens !!!

    node color = bright color
    draw the tree
    node color = normal color
}

可以使用setInterval代替setTimeout。 就像一个循环,迭代之间有延迟。

例如,延迟1秒:

var node_loop = setInterval(function(){
    // Draw a node
}, 1000);

要停止循环:

clearInterval(node_loop);

更多信息: https : //developer.mozilla.org/zh-CN/docs/Web/API/WindowTimers/setInterval

暂无
暂无

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

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