Home  >  Q&A  >  body text

javascript - use of setTimeout

http://ife.baidu.com/course/d...
I am doing a question from Baidu Front-end Academy, the link is as above. The topic is to implement a binary tree traversal. The js code is as follows:

//绑定变量
var root=document.getElementById("root");
var btn1=document.getElementById("btn1");
var btn2=document.getElementById("btn2");
var btn3=document.getElementById("btn3");
var timer=0;
//显示节点
function showNode(node){
    //node.style.backgroundColor = 'red';
    alert(timer);
    setTimeout(function(){
        node.style.backgroundColor="red";
    },timer+=100);
    setTimeout(function(){
        node.style.backgroundColor="#ffffff";
    },timer+=100);
}
//先序遍历
function preOrder(node){
    if(!(node == null)){
        showNode(node);
        preOrder(node.children[0]);
        preOrder(node.children[1]);
    }
}
//使用递归方式实现中序遍历
function inOrder(node){
    if(!(node == null)){
        //alert("btn2");
        inOrder(node.children[0]);//先访问左子树
        showNode(node);//再访问根节点
        inOrder(node.children[1]);//最后访问右子树
    }
}
//后序遍历
function postOrder(node){
    if(!(node == null)){
        postOrder(node.children[0]);
        postOrder(node.children[1]);
        showNode(node);
    }
}
//绑定事件
btn1.onclick=function(){
    preOrder(root);
    timer=0;
}
btn2.onclick=function(){
    inOrder(root);
    timer=0;
}
btn3.onclick=function(){
    postOrder(root);
    timer=0;
}

There is no error in the code, but I just can’t understand why timer =100 is used for the time in setTimeout?
Why can’t I use 100 directly?
I am puzzled. Front-end newbie, please give me some advice!

phpcn_u1582phpcn_u15822662 days ago1029

reply all(2)I'll reply

  • 代言

    代言2017-07-05 10:44:09

    The meaning of this code is that the traversed node is first displayed in red, then in white, and then continues to the next node
    The interval is 0.1 seconds
    Why +=100 instead of 100
    Ignore asynchronous for now, in short
    The execution of the function only takes a moment, and the traversal has been completed. It can be understood as: If the time point of executing the function is 0s, then the execution point of all setTimeout(xxx,100) will be 0.1s later (added to the task queue, the actual execution details The time is not necessarily accurate to 0.1s, but this is not the point, so there is no need to understand the brackets, you will know it later)
    It means that all setTimeout() is completed in an instant (it feels like js will do nothing)

    Then +=100

    means

    setTimeout(xxx,100)
    setTimeout(xxx,200)
    setTimeout(xxx,300).... These will be executed every 0.1s or so

    Take another hole and fill it in later

    reply
    0
  • 三叔

    三叔2017-07-05 10:44:09

    timer+=100, retaining a certain time interval, may be to let you see the process of node traversal with obvious effects.

    reply
    0
  • Cancelreply