简体   繁体   English

Javascript:如何停止计时器并启动计时器

[英]Javascript: How to stop a timer and start a timer

I'm new to Javascript and decided my project for learning and developing further is by making a video game and my current problem is with a timer system. 我是Java语言的新手,因此决定我的进一步学习和开发项目是通过制作视频游戏,而我当前的问题是计时器系统。

Here is the situation. 这是情况。 Your character has energy which will be used up when you use skills. 您的角色拥有的能量会在您使用技能时耗尽。 (Ex: -5 energy loss for X skill). (例如:X技能的能量损失为-5)。 I created a timer for a energy regeneration feature which gives you 1 energy point per second. 我为能量再生功能创建了一个计时器,该计时器每秒为您提供1个能量点。

Now I have two problems with this system. 现在,这个系统有两个问题。 The first one being that when my timer goes off because you reached your CAP energy, it doesn't start regenerating again, so how can I get the timer to continue once it starts to drain? 第一个是当我的计时器由于达到CAP能量而关闭时,它不再开始重新生成,因此一旦计时器耗尽,如何使计时器继续运行?

My second problem is I learned that when i'm actually using the skills, and 5 energy points is being costed, this does not reset the time. 我的第二个问题是我了解到,当我实际使用这些技能并花费5个能量点时,这不会重置时间。 (Ex: 31.. 32.. (use skill -5 energy) 27.. 33.. 34...) So basically it will not register the -5 energy on the timer. (例如:31 .. 32 ..(使用技能-5能量)27 .. 33 .. 34 ...)因此,基本上,它不会在计时器上注册-5能量。

Here is my code. 这是我的代码。

var count = character.energy;
var counter = setInterval(timer, 1000); 

function timer() { 
  count += characterstats.energyregen;
  if (count >= 35){
     clearInterval(counter);
  }

  document.getElementById("energy").innerHTML = count;
  character.energy = count;
}

Why not just add a check for the timer's state when using a skill? 为什么不使用技能时仅添加对计时器状态的检查? You know for a fact when a skill is used, energy is not at maximum - go ahead and start the timer when a skill is used if it's not already running. 您知道一个事实,即使用某项技能时能量没有最大发挥作用-如果尚未使用某项技能,请继续并启动计时器。

function useSkill(skill) {
    if (!isTimerRunning) {
      timer.Start();
    }
    invokeSkillUseMethodHere();
}

1) Add another condition to your if, ie (if count >= 35 && timerRegen == false) and then at the end of your skills add timerRegen = true or something along those lines -- the specifics are murky because I don't follow your entire logic with only seeing your timer 1)在您的if中添加另一个条件,即(if count >= 35 && timerRegen == false) ,然后在您的技能末尾添加timerRegen = true或类似的内容-具体内容不明确,因为我不知道遵循整个逻辑,只看计时器

2) You need to put the time variable outside the scope of the timer function, so that skills alter it. 2)您需要将时间变量置于计时器函数的范围之外,以便技能进行更改。

e-- thank you to the user below for pointing out the errors e-感谢以下用户指出错误

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

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