rohan_vg
rohan_vg

Reputation: 1129

RaphaelJS create rectangle using for loop with interval

Fiddle 1

In this fiddle I have created 5 rectangle shapes on a single row using a for loop. Also I have set an interval between each iteration so that instead of directly displaying 5 rectangles together, they are displayed one by one separated by a small interval. This is one part of my solution. And it is working as intended. Now the problem arises in the next part.


What I actually want to do is create multiple rows and that the rectangle should be displayed one by one on first row and then in the same way on the next row. But there is some mistake in my code due to which instead of displaying one rectangle at a time, entire column is displayed at a time.

Here is the Second Fiddle


I hope you understood what I want to do here. How can I correct the code and get the desired result of displaying rectangle one by one and then advancing to the next row?


for (var i = 0; i < 3 ; i++) {
    for (var j = 0; j < 5; j++) {
        window.setTimeout(
        (function (i,j){ 
            return function() {
                var box = paper.rect(j*100,i*50,100,50);
                box.attr({fill:'yellow'});
            }
        })(i,j),j * 500)
    }
}

Upvotes: 1

Views: 558

Answers (1)

Minko Gechev
Minko Gechev

Reputation: 25672

I think that this solves your problem:

window.onload = function() {

    var ROWS = 3,
        COLS = 5;                

    function drawGrid(paper) {
        for (var i = 0; i < ROWS; i += 1) {
            drawRow(i, paper);
        }
    }

    function drawRow(row, paper) {
        for (var i = 0; i < COLS; i += 1) {
            drawRect(row, i, paper);
        }
    }

    function drawRect(row, col, paper) {
        setTimeout(function () {
            var box = paper.rect(col*100,row*50,100,50);
            box.attr({fill:'yellow'});
        }, (row * COLS * 1000) + (col * 1000));
    }

    drawGrid(Raphael(0, 0, 1920, 1000));
}

​ ​ I just made a little refactoring and calculate the timeout depending on the current column and row.

Here is the fiddle: http://jsfiddle.net/dYRR2/6/

In other words the timeout should be i * 500 * 5 + j * 500 instead of j * 500.

Upvotes: 2

Related Questions