Please look at this codepen: http://codepen.io/dragonOne/pen/rrwrQw (doesn't work yet!)
I want this Javascript memory board to display cards one by one in spiral order.
The spiralOrder(output)
function takes in a matrix of div id
's and changes each card div (id is tile_i
) to display = "block"
one by one in spiral order, every two seconds. But my setTimeout
isn't working properly and is only displaying the first four cards (all at once...)
When I read the console.log
in spiralOrder
I see that the function correctly reads each card in the order that I want. But how come my setTimeout isn't working to add delay after every card display?
function spiralOrder(output) {
// Initialize our four indexes
var top = 0;
var down = output.length - 1;
var left = 0;
var right = output[0].length - 1;
var regexp = /\d+/g;
while(true)
{
// Starting showing top row
for(var j = left; j <= right; ++j) {
console.log("tile_"+output[top][j].match(regexp)); //THIS SHOWS SPIRAL ALGORITHM IS CORRECT
setTimeout(function() { document.getElementById("tile_"+output[top][j].match(regexp)).style.display = "block"; }, 2000); //THIS DOESN'T BEHAVE RIGHT
}
top++;
if(top > down || left > right) {
break;
}
//Starting showing rightmost column
for(var i = top; i <= down; ++i){
console.log("tile_"+output[i][right].match(regexp));
setTimeout(function() { document.getElementById("tile_"+output[i][right].match(regexp)).style.display = "block"; }, 2000);
}
right--;
if(top > down || left > right) {
break;
}
//Starting showing bottom row
for(var j = right; j >= left; --j){
console.log("tile_"+output[down][j].match(regexp));
setTimeout(function() { document.getElementById("tile_"+output[down][j].match(regexp)).style.display = "block"; }, 2000);
}
down--;
if(top > down || left > right) {
break;
}
//Starting showing leftmost column
for(var i = down; i >= top; --i){
console.log("tile_"+output[i][left].match(regexp));
setTimeout(function() { document.getElementById("tile_"+output[i][left].match(regexp)).style.display = "block"; }, 2000);
}
left++;
if(top > down || left > right) {
break;
}
}
}
What is going wrong here?