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.

4
  • 1
    for-loop is non-blocking Commented Apr 20, 2016 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. Commented Apr 20, 2016 at 13:11
  • Thanks @RayonDabre , What should I do then? Commented Apr 20, 2016 at 13:11
  • 1
    Check this out stackoverflow.com/questions/3583724/… Commented Apr 20, 2016 at 13:12

2 Answers 2

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

Sign up to request clarification or add additional context in comments.

Comments

1

Use setInterval() instead of setTimeout

1 Comment

That is not a useful answer.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.