计时器使用JavaScript

sar*_*der 3 html javascript timer countdown

我想使用java脚本实现计时器.我想减少间隔变化的计时器.
示例.假设我的计时器从500开始.
我希望减量计时器取决于如
1的水平.第1级计时器应减1,减速也应该慢.
2.2级定时器应减2,减速应为中
3.3级定时器应减3,减速应快

我可以使用以下代码创建计时器:

<script type="text/javascript">
var Timer;
var TotalSeconds;
function CreateTimer(TimerID, Time) 
{
    TotalSeconds=Time;
    Timer = document.getElementById(TimerID);
    TotalSeconds = Time;
    UpdateTimer();
    setTimeout("Tick()", 1000);
}

function Tick() {
    TotalSeconds -= 10;
    if (TotalSeconds>=1)
    {
        UpdateTimer();
        setTimeout("Tick()", 1000);
    }
    else
    {   
        alert(" Time out ");
        TotalSeconds=1;
        Timer.innerHTML = 1;
    }
}
Run Code Online (Sandbox Code Playgroud)

但我多次调用这个CreateTimer()函数,因此它的速度不受控制,因为我多次调用它.

Rob*_*obG 5

几点:

  1. 您已经使用了所有全局变量,最好将它们保密,以便其他函数不会混淆它们
  2. 按惯例,以字母开头的函数名称保留给构造函数
  3. 分配给setTimeout的函数没有任何公共变量或函数来在运行时修改速度,因此您只能使用全局变量来控制速度.如果你不关心别人搞乱他们,那就没关系,但更好的办法就是让他们保密
  4. 代码UpdateTimer尚未包含在内
  5. 不是将字符串传递给setTimeout,而是传递函数引用: setTimeout(Tick, 1000);

无论如何,如果你想要一个简单的计时器,你可以改变速度:

<script>

var timer = (function() {
    var basePeriod = 1000;
    var currentSpeed = 1;
    var timerElement;
    var timeoutRef;
    var count = 0;

    return {
      start : function(speed, id) {
        if (speed >= 0) {
          currentSpeed = speed;
        }
        if (id) {
          timerElement = document.getElementById(id);
        }
        timer.run();
      },

      run: function() {
        if (timeoutRef) clearInterval(timeoutRef);
        if (timerElement) {
          timerElement.innerHTML = count;
        }
        if (currentSpeed) {
          timeoutRef = setTimeout(timer.run, basePeriod/currentSpeed);
        }
        ++count;
      },

      setSpeed: function(speed) {
        currentSpeed = +speed;
        timer.run();
      }
    }

}());

window.onload = function(){timer.start(10, 'timer');};

</script>

<div id="timer"></div>
<input id="i0">
<button onclick="
  timer.setSpeed(document.getElementById('i0').value);
">Set new speed</button>
Run Code Online (Sandbox Code Playgroud)

它将所有变量保存在闭包中,因此只有函数才能修改它们.您可以通过将速度设置为零来暂停它.