gpt4 book ai didi

javascript - setTimeout 和 setInterval 未按预期工作

转载 作者:行者123 更新时间:2023-12-02 19:46:35 25 4
gpt4 key购买 nike

我似乎无法让它工作,应该发生的是当用户按下空格键时。 event.which=32 它确实移动了,但它向上移动了 20 个,并且一次总共移动了 20 个,它不会每秒或 1000 毫秒 1 乘 1 移动

$(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);
});

});

最佳答案

您正在通过 for 循环同时设置所有 setTimeout。您需要等待才能调用下一个。

if (prekey==39) { 
var count = 0,
jumpBox;
jumpBox = function() {
x=x+1;
y=y-1;
ctx.clearRect (0, 0, 500, 300);
ctx.fillRect (x, y, w, h);

if(++count < 20) {
setTimeout(jumpBox, 1000);
}
}
var t = setTimeout(jumpBox, 1000);
}

关于javascript - setTimeout 和 setInterval 未按预期工作,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9812112/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com