5秒倒计时器

时间:2015-02-09 02:57:17

标签: javascript html 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();

})();

2 个答案:

答案 0 :(得分:0)

使用setInterval以小间隔(例如50ms)更新计时器显示。

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

答案 1 :(得分:-1)

在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;