javascript - setTimeout() 在 JavaScript 中如何工作?

标签 javascript html css settimeout

<分区>

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

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);     
}  

任何帮助将不胜感激。

最佳答案

for-loop is non-blocking, all the setTimeout instances in a loop will execute once duration specified is completed.

维护一个计数器并将其用作setTimeout() 中的毫秒参数,这样循环中的每个处理程序都将在100(100,200,300,...)的倍数

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);
}

关于javascript - setTimeout() 在 JavaScript 中如何工作?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36744744/

上一篇:html - 当被迫分成两行时,如何使列表中的间距更大?

下一篇:html - 为什么不在 <li> 中阻止 <a> 接受 css 文件中设置的颜色?

相关文章:

css - 当使用附件固定且边距不起作用时,标题图像位于导航栏后面

javascript将值分配给函数中的全局变量不起作用

html - 彼此相邻的位置按钮

javascript - jQuery UI效果 "shake"使div消失

javascript - 将视频从 DirectX 流式传输到 HTML5

jquery - 可以通过 jQuery html() 方法设置数据的最大限制是多少

php - JQuery Mobile 样式保留在我链接到的页面中

javascript - 使用 React Native 创建平面图

javascript - 如何从网页中提取文本

javascript - HTML Canvas : drawing separated circles