<分区>
<分区>
在我的代码中,我想画一条线。为此,我根据线方程放置点。而且我还希望在打印下一个点之前延迟 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
isnon-blocking
, all thesetTimeout
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/