简体   繁体   English

Javascript - 停止所有函数的执行

[英]Javascript - Stop all functions from executing

I am a beginner in progamming and just wrote my first game with HTML, CSS and vanilla JavaScript.我是一名编程初学者,刚刚用 HTML、CSS 和原版 JavaScript 编写了我的第一款游戏。 It is working fine but now I am facing an issue while trying to implement a restart-function.它工作正常,但现在我在尝试实现重启功能时遇到了问题。 I found similar questions and tried a lot but couldn't find a way to solve this: I wrapped the whole game in a function and added an event listener to a button to start the game:我发现了类似的问题并尝试了很多,但找不到解决方法:我将整个游戏包装在 function 中,并在按钮中添加了一个事件监听器来开始游戏:

game() { /*game code*/ }
gameButton.addEventListener("click", game);

Inside the code I got multiple functions and eventListeners.在代码中,我得到了多个函数和 eventListeners。 There are three ways to "die" and get an Game Over-message.有三种方式“死亡”并获得游戏结束消息。 This is when the game button reappears.这是游戏按钮重新出现的时候。 However, when you click it, the game()-function is still running and the game isn't working, the way it should anymore.但是,当您单击它时,game() 函数仍在运行,并且游戏无法正常运行。 I tried to figure out how to stop the whole game-function in case one of these events happens but without success.我试图弄清楚如何停止整个游戏功能,以防这些事件之一发生但没有成功。

So, for example: if you click at the wrong place, a failed-function gets triggered and your score will be decreased by 1. If your score is below 1, you die and the game is over:所以,例如:如果你点击了错误的地方,一个失败的功能被触发,你的分数将减 1。如果你的分数低于 1,你就死了,游戏结束了:

function failed() {

    let x = parseInt(score.innerText) - 1;
    score.innerText = x.toString();
    if (x < 1) {
      gameOverText.style.display = "block";
    }

How I can I stop the game()-function from here?我怎样才能从这里停止游戏()功能?

Thank you very much in advance!非常感谢您!

It really depends on the actual code and design.这实际上取决于实际的代码和设计。 But the easiest way is a boolean.但最简单的方法是 boolean。 and in your methods check to make sure it is still running并在您的方法中检查以确保它仍在运行

var isActive = true
function failed() {
  if (!isActive) return
  ...

so when the game is over, you set isActive to false所以当游戏结束时,你将 isActive 设置为 false

Did you try to attach/remove listener based on event output.您是否尝试根据事件 output 附加/删除侦听器。 Or you can check for condition and return early或者您可以检查状况并提前返回

pseudo code:伪代码:

const game = () => {
    // Do something here

    if(isDisabled) {
        return 
    }

    // OR

    if(something_to_stop) {
        detachListeners()
    }
}
function attachListeners() {
    gameButton.addEventListener("click", game);
}
function detachListeners() {
    gameButton.removeListener("click", game);
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM