javascript - setTimeout 和 setInterval 未按预期工作

标签 javascript jquery html

我似乎无法让它工作,应该发生的是当用户按下空格键时。 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/

相关文章:

javascript - 我如何创建我自己的 watch 功能类似于javascript中的 Angular

javascript - 慢点,控制台。 (javascript/jquery)

javascript - 将 html.beginform 内的 Dropdown 值传递给 ajax 操作调用

javascript - 当触发响应式 jQuery 函数时,该函数不会停止触发

javascript - 如何遍历数组并运行 Grunt 任务,将数组中的每个值作为 Grunt 选项传递

javascript - 通过 jQuery 引入样式变化

html - 为什么在尝试假设 divs 的高度时相对定位不起作用?

javascript - 单击外部 div 以关闭 div

html - 用 100vh 定义的 div 容器的高度太大(看起来它根据窗口大小定位自身)

javascript - 不可变 js 和 redux 存储中的函数