【问题标题】:cancel timeOut in JavaScript with a button使用按钮取消 JavaScript 中的超时
【发布时间】:2016-09-10 21:26:54
【问题描述】:

我试图在我的游戏中使用一个按钮来停止 setTimeout,但是当我单击该按钮时,我会返回菜单并且计时器会继续。有人可以帮我吗?

附:我在中间剪掉了很多代码以使其更小

       this.stop();
    ///////////////////////////////////////////////////////////////////////////////////////////////////////
    // gestion du temps
    ///////////////////////////////////////////////////////////////////////////////////////////////////////
    this.leTimeOut = window.setTimeout(punir.bind(this), 31000);
    this.lInterval = window.setInterval(afficherTemps.bind(this), 1000);
/////////////////////////
Cutted section
////////////////////////

        console.info("!!! "+nbMatchs+" !!!");
        this.txtItems.text = ""+(6-nbMatchs);

        if(nbMatchs == 6){
            window.clearTimeout(this.leTimeOut);
            this.gotoAndStop("FinNiveau1");
        }

        return bonnePosition;
    }


    ///////////////////////////////////////////////////////////////////////////////////////////////////////
    // Fonction pour lancer la punition
    ///////////////////////////////////////////////////////////////////////////////////////////////////////
    function punir(evt){
        console.log("temps écoulé"); 
        this.gotoAndStop("EchecNiveau1");
    }


    ///////////////////////////////////////////////////////////////////////////////////////////////////////
    // Fonction d'affichage du temps
    ///////////////////////////////////////////////////////////////////////////////////////////////////////
    this.txtTimer.text = "29";
    function afficherTemps(evt){
        this.txtTimer.text = parseInt(this.txtTimer.text)-1;
    }


    ///////////////////////////////////////////////////////////////////////////////////////////////////////
    // Fonction et écouteur du bouton Annuler
    ///////////////////////////////////////////////////////////////////////////////////////////////////////
    this.btRetour.evenementClick = this.btRetour.on("click", onClicA);
    function onClicA(evt) {
        console.log("retour au menu");
        clearTimeOut(this.leTimeOut);   
        evt.remove(); //retrait de l'écouteur (la méthode facile!)
        this.parent.gotoAndStop("Intro");

    }

【问题讨论】:

  • 你能把你的代码作为代码块放在问题中吗?从图像中查看代码非常困难。
  • 您应该提供代码。否则,你会收集反对票
  • 你去。现在应该更好

标签: javascript settimeout cleartimeout


【解决方案1】:

如果您的代码完全复制了您的“clearTimeout” 是 clearTimeOut 并且超时中的 o 不应该大写

【讨论】:

  • 太糟糕了,我在尝试查找错误时更改了它,但我只是将其更改回来,当我单击按钮时,30 秒后仍然出现丢失屏幕。
  • 接下来我要检查的是 timerId 是否相同,所以当你第一次声明 this.leTimeOut 时,我会在它下面放一个 console.log(this.leTimeOut) 并在你调用 @987654323 之前做同样的事情@ 并确保它们在控制台中返回相同的 id
  • 感谢您的想法,我发现了问题。简单地说,在我的 clearTimeOut 期间,我需要放置 (this.parent.ltTimeOut) 以使其工作。
  • 太棒了!很高兴这有效,通常总是一些愚蠢的东西导致问题大声笑和控制台日志记录可以成为你找出它是什么的最好的朋友
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2013-06-14
  • 2011-10-21
  • 1970-01-01
  • 2023-03-18
  • 1970-01-01
相关资源
最近更新 更多