Reputation: 3517
Update: I edited the setTimeout()
code to run the code inside a function, but now nothing runs at all. I also changed the function to accept drawcount
, i
, and j
, making the call appendcharacter(drawcount, i, j)
. It still does nothing at all (although originally it ran, all at the same time). For some reason setTimeout
is not running the function properly after the timeout.
--Original Question--
I have the following code (note not all variables are listed, just what was relevant or was with this section of code). I would like to stagger the running of appendcharacter(drawcount)
so that it will run in half-second intervals, yet this code runs everything at exactly the same time:
var $span, $br;
var $img = $('#image');
$(document).ready(function () {
var drawcount = 0;
for (var j = 0; j < imgwidth; j++) {
$("#image").append("<br>");
for (var i = 0; i < imgheight; i++) {
var timeout = 500 * drawcount;
console.log(timeout);
setTimeout(function () {
appendcharacter(drawcount, i, j);
},timeout);
drawcount++;
}
}
function appendcharacter(drawcount, i, j) {
$span = $("<span id='" + i + "_" + j + "' style='position:relative; display: inline; color: rgba(" + pixels[j][i].red + " , " + pixels[j][i].green + " , " + pixels[j][i].blue + ", 1);'></span>").appendTo($img);
switch (drawcount % 18) {
case 0:
$("#" + i + "_" + j).append("/");
break;
case 2:
$("#" + i + "_" + j).append("-");
break;
case 3:
$("#" + i + "_" + j).append("/");
break;
case 4:
$("#" + i + "_" + j).append("-");
break;
case 5:
$("#" + i + "_" + j).append("/");
break;
case 6:
$("#" + i + "_" + j).append("-");
break;
case 7:
$("#" + i + "_" + j).append("(");
break;
case 8:
$("#" + i + "_" + j).append("8");
break;
case 9:
$("#" + i + "_" + j).append("8");
break;
case 10:
$("#" + i + "_" + j).append(")");
break;
case 11:
$("#" + i + "_" + j).append("-");
break;
case 12:
$("#" + i + "_" + j).append("\\");
break;
case 13:
$("#" + i + "_" + j).append("-");
break;
case 14:
$("#" + i + "_" + j).append("\\");
break;
case 15:
$("#" + i + "_" + j).append("-");
break;
case 16:
$("#" + i + "_" + j).append("\\");
break;
case 17:
$("#" + i + "_" + j).append(" ");
break;
}
}
});
Upvotes: 0
Views: 82
Reputation: 388436
You are invoking the function appendcharacter
and passing the value returned by it as the callback to the setTimeout
method.
You need to pass a function reference to the setTimeout
which will get invoked, you also need to use a local closure function because of the reference to shared variable drawcount
in the callback
(function(drawcount, i, j){
setTimeout(function () {
appendcharacter(drawcount, i, j);
}, timeout);
})(drawcount, i, j)
You also need to pass i and j as aprams to appendcharacter
ex
function appendcharacter(drawcount, i, j) {
..
}
Upvotes: 1