首页 > 解决方案 > 垃圾邮件异步回调打破了我的 setTimeout 延迟

问题描述

因此,当玩家按下 x 时,我的角色 div 会更改其背景图像,如果角色接触到敌人,则会杀死敌人。这个图像切换是做一个挥剑的模拟动画。

我使用 set timeout 来延迟将背景图像切换回其原始状态。这行得通。

但是他们的错误是,如果我发送垃圾邮件 x,则图像切换之间不再有延迟,我假设原因与从 setTimeout 函数堆叠异步回调有关,该函数在播放器发送垃圾邮件 x 时被调用。

** 在此函数中调用设置超时 **

function pressOn(e) {
    e.preventDefault();
    let tempKey = (e.key == " ") ? "space" : e.key;
    keys[tempKey] = true;

         if (keys['x'] && player.swing == false){
              player.plane.style.backgroundImage ='url(guts2.png)';
                 setTimeout(function () {
                 player.swing = true;
                 }, 300);
          }

 }

** 将背景图像还原为原始图像 **

function playGame() {
   if (player.inplay) {

       if (player.swing && !keys['x']){
             player.plane.style.backgroundImage ='url(guts1.png)';
             player.swing = false;
        }

    window.requestAnimationFrame(playGame);
    }
}

** JS FIDDLE 完整项目的链接**

https://jsfiddle.net/mugs17/sud2ojxy/17/

标签: javascript

解决方案


您的逻辑在 setTimeout 中是落后的。您希望将 swing 自动设置为 true(这将阻止 if 语句执行)并在 setTimeout 回调中将其设置回 false。

- 这是解决方案:

let player = {
       swing: false
}

-

function pressOn(e) {
    e.preventDefault();
    let tempKey = (e.key == " ") ? "space" : e.key;
    keys[tempKey] = true;

    if (keys['x'] && player.swing == false) {

        player.plane.style.backgroundImage = 'url(guts2.png)';
        player.swing = true;

        setTimeout(function () {

            player.plane.style.backgroundImage = 'url(guts1.png)';
            player.swing = false;

        }, 1000);

}

推荐阅读