使用可轻松重置的代码制作计时器

时间:2016-02-11 03:12:49

标签: javascript timer key-bindings stopwatch

我为学校的篮球队制作了一个投篮钟。拍摄时钟是一个从24秒倒计时的计时器。我现在有计时器的骨架,但我需要有特定的键绑定。键绑定应该允许我休息,暂停和播放计时器。

var count=24;

var counter=setInterval(timer, 1000);

function timer()
{
  count=count-1;
  if (count <= 0)
  {
     clearInterval(counter);
     return;
  }

 document.getElementById("timer").innerHTML=count + " secs";
}

3 个答案:

答案 0 :(得分:0)

我暂时无法发表评论,但我建议您查看此帖子Binding arrow keys in JS/jQuery

链接的帖子解释了如何使用js / jquery绑定箭头键。使用http://keycode.info/,您可以找到所需密钥的密钥代码并替换当前值,然后继续从那里构建代码。

答案 1 :(得分:0)

我不确定你的意思是什么?&#34;休息&#34;计时器,我把它解释为&#34;暂停&#34;。

空格 =暂停/播放。

r =重置

<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <title>Document</title>
</head>
<body id="body">

  <div id="timer">24 secs</div>
  <script>
  var count=24, counter=setInterval(timer, 1000),running = true;

  function timer() {
    count-=1;
    if (count <= 0) {
      clearInterval(counter);
    }
    document.getElementById("timer").innerHTML=count + " secs";
  }
  window.addEventListener("keydown", function(e){
    switch(e.keyCode){
      case 32:// PLAY
      running ? clearInterval(counter) : counter=setInterval(timer, 1000);
      running = !running;
      break;
      case 82: // RESET
      clearInterval(counter);
      document.getElementById("timer").innerHTML=24 + " secs";
      count = 24;
      running = false;
    }
  });

  </script>
</body>
</html>

答案 2 :(得分:0)

以下是我的代码示例:http://codepen.io/anon/pen/vLvWJM

$(document).ready(function() {
  var $timer = $('#timer');
  var $timerStatus = $('#timerStatus');
  var timerValue = 24;
  var intervalId = null;
  var timerStatus = 'stopped';
  
  if(!$timer.length) {
    throw 'This timer is missing a <div> element.';
  }
  
  $(document).keydown(function(k) {
    if(k.which == 80) {
      if(timerStatus === 'playing') {
        clearInterval(intervalId);
        timerStatus = 'stopped';
        updateTimerStatus();
        return;
      }
      
      intervalId = setInterval(function() {
        playTimer();
        timerStatus = 'playing';
        updateTimerStatus();
      }, 1000);
    } else if(k.which == 82) {
      clearInterval(intervalId);
      resetTimer();                              
      updateText();
      timerStatus = 'stopped';
      updateTimerStatus();
    }
  });
  
  function playTimer() {
    if(timerValue > 0) {
      timerValue--;
      updateText();
    }
  }
  
  function resetTimer() {
    timerValue = 24;
  }
  
  function updateText() {
    $timer.html(timerValue);
  }
  
  function updateTimerStatus() {
    $timerStatus.html(timerStatus);
  }
});
<div id="timerStatus">stopped</div>
<div id="timer">24</div>