简体   繁体   English

重置计时器?

[英]Resetting a timer?

I'm having a bit trouble resetting a countdown timer. 重置倒数计时器我有点麻烦。 Here is the JSFiddle . 这是JSFiddle It's basically a simple game where you have 5 seconds to select the word that is an anagram of a given word. 它基本上是一个简单的游戏,你有5秒的时间来选择一个给定单词的字谜。

I'm basically trying to create a resetTimer() function (line 166) that will put the timer back to 5:00 if you've selected the correct answer. 我基本上试图创建一个resetTimer()函数(第166行),如果您选择了正确的答案,它将把计时器恢复到5:00。

This is the place in my code where I want to call the resetTimer() function. 这是我想在代码中调用resetTimer()函数的地方。

  view.updateData = function() {
    view.assignWords();
    view.displayTimer();

    for(var i = 0; i < this.buttons.length; i++) {
      this.buttons[i].addEventListener('click', function(event) {
        if(event.target === dictionary.correctButton) {
          dictionary.words.pop(this.currWord);
          dictionary.updateWordCount();
          view.assignWords();
          view.updateScore();
          view.resetTimer();
        } else {
          view.displayLossScreen();
        }
      });
    }
  };

And this is the code for my timer which starts at 5:00 and goes down to zero. 这是我的计时器的代码,它从5:00开始并下降到零。

  view.displayTimer = function() {
    var count = 500;
    var timer = setInterval(countdown, 10);

    function countdown() {
      if(count === 0) {
        clearInterval(timer);
        view.displayLossScreen();
      } else {
        count--;
      }
      document.getElementById("timer").innerHTML = (count / 100).toFixed(2);
    }
  };

Any help would be very much appreciated! 任何帮助将非常感谢!

Consider following changes: 考虑以下更改:

First setting count as global variable: 首先将计数设置为全局变量:

var count = 500;//global variable

view.resetTimer = function() {
    count=500;
  };

UPDATED DEMO 更新的演示

Updates: 更新:

Timer was going fast and faster because of line: 由于线路,计时器变得越来越快:

var timer = setInterval(countdown, 10);//setting new variable with interval every time

I have set timer as a global variable, and clearing it every time before starting: 我已将timer设置为全局变量,并在每次启动前清除它:

var timer;//setting global variable
clearInterval(timer);//clearing timer
timer = setInterval(countdown, 10); 

Fixed DEMO 修复了DEMO

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

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