0

In my code, I want to draw a line. For that I am putting points according to the equation of line. And I also want delay of 100 milliSec before next point is printed. So, I used setTimeout(). But when I run this code, first it waits for some time and then prints all the point at a time without delay of 100ms. Here is my code for drawing line:

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

Any help will highly be appreciated.

RobG
  • 142,382
  • 31
  • 172
  • 209
No Sound
  • 113
  • 1
  • 11
  • 1
    `for-loop` is `non-blocking` – Rayon Apr 20 '16 at 13:09
  • 1
    *setTimeout* does not pause the loop, so they are effectively all set at the same instant with the same delay. Also, additional arguments beyond 2 are not supported by all browsers. – RobG Apr 20 '16 at 13:11
  • Thanks @RayonDabre , What should I do then? – No Sound Apr 20 '16 at 13:11
  • 1
    Check this out http://stackoverflow.com/questions/3583724/how-do-i-add-a-delay-in-a-javascript-loop – eol Apr 20 '16 at 13:12

2 Answers2

2

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

Maintain a counter and use it as a milliseconds argument in setTimeout() so that every handler in a loop will be invoked in the multiples of 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);
}
Rayon
  • 36,219
  • 4
  • 49
  • 76
1

Use setInterval() instead of setTimeout

Harish Kumar
  • 133
  • 6