setTimeout()如何在JavaScript中运行?

时间:2016-04-20 13:04:49

标签: javascript html css settimeout

在我的代码中,我想画一条线。为此,我根据线的方程式加点。而且我还希望在打印下一个点之前延迟100毫安。所以,我使用了setTimeout()。但是当我运行这段代码时,首先它等待一段时间,然后一次打印所有点,没有延迟100ms。 这是我绘制线的代码:

function drawLine(x1, y1,x2,y2){

    var x, y, m;
    m=(y2-y1)/(x2-x1);

    for(x=x1;x<=x2;x++){
        y=(m*(x-x1)+y1)/6;
        setTimeout(drawPoint,100,x,y);
    }

}

function drawPoint(a,b){

    main=document.getElementById("main");     //parent div tag in which children div tags are to be appended
    var children=main.childNodes;
    var child=document.createElement("div");

    child.className="anime";
    child.style.left=a+"px";
    child.style.top=300-b+"px";             //300 is some offset

    main.appendChild(child);     
}  

任何帮助都将受到高度赞赏。

2 个答案:

答案 0 :(得分:1)

  

for-loopnon-blocking,一旦指定的持续时间完成,循环中的所有setTimeout个实例都将执行。

维护counter并将其用作milliseconds中的setTimeout()参数,以便循环中的每个处理程序将以100(100,200,300,...)的倍数调用。 ..)

&#13;
&#13;
function drawLine(x1, y1, x2, y2) {
  var x, y, m;
  m = (y2 - y1) / (x2 - x1);
  var counter = 1;
  for (x = x1; x <= x2; x++) {
    y = (m * (x - x1) + y1) / 6;
    setTimeout(drawPoint, (100 * counter), x, y);
    ++counter;
  }
}

function drawPoint(a, b) {
  main = document.getElementById("main"); //parent div tag in which children div tags are to be appended
  var children = main.childNodes;
  var child = document.createElement("div");
  child.className = "anime";
  child.style.left = a + "px";
  child.style.top = 300 - b + "px"; //300 is some offset
  main.appendChild(child);
}
&#13;
&#13;
&#13;

答案 1 :(得分:1)

使用setInterval()代替setTimeout

相关问题