5 秒倒数计时器

5-second count down timer

我有一个简单的问题。我正在尝试为我的第一个项目添加一个倒计时计时器。我打算将计时器放在页面顶部,我希望它显示从 5:00 到 0:00 的当前剩余时间。我知道如何使用 setInterval 来做到这一点,它可以每秒执行类似 time-- 的操作,但我希望它也显示当前的毫秒数,但我不确定该怎么做。非常感谢任何帮助!

这是我到目前为止编写的代码,现在它在 assignWords() 方法中使用了 5 秒超时。

(function () {
  'use strict';

  // Dictionary object used to manipulate anagrams
  var dictionary = {};

  // List of letters used to help create incorrect choices
  dictionary.letters = [
  'a', 'b', 'c', 'd', 'e', 'f',
  'g', 'h', 'i', 'j', 'k', 'l',
  'm', 'n', 'o', 'p', 'q', 'r',
  's', 't', 'u', 'v', 'w', 'x',
  'y', 'z'];

  // List of words that are used for anagram questions
  dictionary.words = [
  'adaxial', 'agreeably', 'antinoise', 'asthenia', 'astint', 'babushka', 'bailiffry', 'bathtub', 'bestab', 'bestiary', 'bibulous', 'bordage', 'bostonite', 'brogue', 'brushoff', 'budlet', 'cathepsin', 'centesimi', 'chaste', 'chicayote', 'coastal', 'coppice', 'couple', 'cuapinole', 'cytoplasm', 'daubingly', 'dearth', 'deasil', 'drightin', 'drudge', 'ejecta', 'feelable', 'fistnote', 'flareback', 'folial', 'fortunate', 'garrulous', 'gemmology', 'glaringly', 'gleet', 'globule', 'gluepot', 'googol', 'googul', 'humuslike', 'ichnology', 'illiberal', 'issite', 'karyotin', 'kella', 'ketol', 'knowingly', 'lysogenic', 'macaque', 'meddle', 'menseful', 'mocha', 'mournival', 'musher', 'natty', 'nonactive', 'nonserous', 'outcut', 'outspeak', 'overheavy', 'partially', 'pernor', 'picnic', 'prickwood', 'pyorrheal', 'redly', 'refine', 'regaler', 'rollick', 'sandling', 'sarcastic', 'scypha', 'severely', 'sinkage', 'sissyish', 'sogging', 'staling', 'steellike', 'stonelike', 'stoneware', 'tadpolism', 'tarditude', 'tazia', 'thymiosis', 'tightener', 'tritical', 'trundler', 'undenuded', 'underbank', 'unpaining', 'untraded', 'wayfare', 'woodworm', 'woofer', 'zemeism'];

  // Stores the count of the remaining words
  dictionary.wordCount = dictionary.words.length;

  /*
  *  Returns a random letter from dictionary.letters
  */
  dictionary.randLetter = function () {
    return this.letters[Math.floor(Math.random() * 100 % 26)];
  };

  /*
  *  Replaces one letter of a word with a randomly selected letter
  */
  dictionary.replaceLetter = function (word) {
    var index = Math.floor(Math.random() * 100 % word.length);
    var newWord = word.slice(0, index) + word.slice(index + 1);
    return newWord += this.randLetter();
  };

  /*
  *  Returns a random word from dictionary.words
  */
  dictionary.randWord = function () {
    return this.words[Math.floor(Math.random() * 100 % this.wordCount)];
  };

  /*
  *  Randomly shuffles the letters around in a word
  */
  dictionary.shuffle = function (word) {
    var fragments = word.split('');
    for (var i = fragments.length; i > 0;) {
      var random = parseInt(Math.random() * i);
      var temp = fragments[--i];
      fragments[i] = fragments[random];
      fragments[random] = temp;
    }
    return fragments.join('');
  };

  /*
  *  Returns the correct answer for the current word
  */
  dictionary.getCorrectChoice = function (word) {
    return this.shuffle(word);
  };

  /*
  *  Returns an incorrect answer for the current word
  */
  dictionary.getIncorrectChoice = function (word) {
    word = this.replaceLetter(word);
    return this.shuffle(word);
  };

  /*
  *  Randomly assigns the current word and correct and incorrect choices to the four buttons
  */
  function assignWords() {
  // Clear the timeout for the previous question
  window.clearTimeout(dictionary.timeout);

  // Allow 5 seconds for the user to get the right answer
  dictionary.timeout = window.setTimeout(function() {
    alert('you lose!');
  }, 5000);

  var currWord = document.getElementById('currentWord');
  var buttons = document.getElementsByTagName('button');

  // Randomly choose a word to use as the anagram test
  currWord.innerHTML = dictionary.randWord();

  // Randomly choose a button to hold the correct choice
  dictionary.correctButton = buttons[Math.floor(Math.random() * 4)];
  dictionary.correctButton.innerHTML = dictionary.getCorrectChoice(currWord.innerHTML);

  // Give the rest of the buttons incorrect choices
  for (var i = 0; i < buttons.length; i++) {
    if (buttons[i] === dictionary.correctButton) {
      continue;
    } else {
      buttons[i].innerHTML = dictionary.getIncorrectChoice(currWord.innerHTML);
    }
  }
}

  // View object used to change information displayed on the page
  var view = {};

  // Stores the player's current score
  view.score = 0;

  // The timer that has the remaining time to answer the question
  view.timer = 0;

  // 
  view.resetData = function() {

  };

  view.displayData = function() {
    assignWords();
    var buttons = document.getElementsByTagName('button');
    for(var i = 0; i < buttons.length; i++) {
      buttons[i].addEventListener('click', function(event) {
        if (event.target === dictionary.correctButton) {
          assignWords();
        }
      });
    }
  };

  view.displayData();

})();

在 W3C 网站上找到了类似的代码,认为它可能就是您要找的代码:

        var d = new Date();
        var x = document.getElementById("demo");
        var h = d.getHours();
        var m = d.getMinutes();
        var s = d.getSeconds();
        var ms = d.getMilliseconds();
        x.innerHTML = h + ":" + m + ":" + s + ":" + ms;

使用 setInterval 以较小的间隔(例如 50 毫秒)更新您的计时器显示。

要获得剩余时间,而不是每秒将计数器减 1,只需记下开始时间并从当前时间中减去它。这将为您提供自计时器启动以来经过的总毫秒数,然后您可以格式化显示。