Reputation: 45
I made a maze application with a route finder. As it travels along the route, it makes a call to draw the canvas, highlighting each cell en route. However what ends up happening is it blocks until it has completely finished and then draws to the canvas. Roughly like so:
Path.prototype.travelTo (cell) {
this.previous = this.cell;
this.cell = cell;
this.cell.fill = 'yellow';
this.maze.draw();
var choice = findChoice();
this.travelTo(choice);
};
The maze class keeps track of all cells and its draw function loops through each cell, calling the cells own draw function.
I made a quick jsfiddle (http://jsfiddle.net/amctammany/99VVu/) that emulates the problem. Here it travels from one cell to the next by recursively calling itself via setTimeout. The result is the same, it instantly fills all cells, without even waiting for any amount of time.
Any help would be appreciated.
Upvotes: 0
Views: 71
Reputation: 2565
I had a look at your jsfiddle, and the first thing I noticed is your setTimeout:
window.setTimeout(fillNext(i + 1), 500);
But probably you meant to do this:
window.setTimeout(function() {fillNext(i + 1)}, 500);
You should set the fillNext(i+1)
as a callback to setTimeout
,
not use the return value of fillNext(i+1)
as the argument of window.setTimeout()
Upvotes: 2
Reputation: 582
Update the following line as given below.Then you can see the animation.
"window.setTimeout(fillNext(i + 1), 500);" To "window.setTimeout(fillNext, 100,(i + 1));"
I have updated the fiddle.You can check it now.
Upvotes: 0