I can’t seem to get this working, what should happen is when the user presses the spacebar ie. event.which=32 it does move but it moves 20 up and 20 over all at once it doesn’t go 1 by 1 every second or 1000 milliseconds
$(function() {
var canvas = document.getElementById('canvas');
var ctx = canvas.getContext('2d');
var x =0;
var y =100;
var w =50;
var h =50;
var prekey = '';
ctx.fillStyle = "rgb(200,0,0)";
ctx.fillRect (x, y, w, h);
var i=0; var hi = '';
$("*").keydown(function(event) {
ctx.clearRect (0, 0, 500, 300);
if (event.which == 37){
if (x!=0){x=x-1;} prekey=event.which;
}
if (event.which == 39){if (x!=450){x=x+1;} prekey=event.which;}
if (event.which == 32) {
if (prekey==39) {
for(i=0;i<=20;i++) {
function jumpBox() {
x=x+1;
y=y-1;
ctx.clearRect (0, 0, 500, 300);
ctx.fillRect (x, y, w, h);
return 1;
}
var t = setTimeout(jumpBox, 1000);
}
if (prekey==37){}
}
ctx.fillRect (x, y, w, h);
});
});
You are setting all your
setTimeouts at the same time through the for loop. You need to wait before calling the next one.