使用相同的功能创建多个对象

时间:2013-03-07 00:08:03

标签: javascript jquery

我有一个倒计时到0的计时器。它适用于一个,但我想在同一页面上创建第二个计时器。我可以创建第二个计时器,但它不会倒计时,第一个倒计时的速度提高两倍。我该怎么做这是我的代码

<script>
var Timer;
var TotalSeconds;

function CreateTimer(TimerID, Time) {
  Timer = document.getElementById(TimerID);
  TotalSeconds = Time;
  UpdateTimer()
  window.setTimeout("Tick()", 1000);
}

function Tick() {
  if(TotalSeconds <= 0) {
    TotalSeconds = 0;
    return;
  }

  TotalSeconds -= 1;
  UpdateTimer()
  window.setTimeout("Tick()", 1000);
}

function UpdateTimer() {
  var Seconds = TotalSeconds;
  var Days = Math.floor(Seconds / 86400);
  Seconds -= Days * 86400;
  var Hours = Math.floor(Seconds / 3600);
  Seconds -= Hours * (3600);
  var Minutes = Math.floor(Seconds / 60);
  Seconds -= Minutes * (60);
  var TimeStr = ((Days > 0) ? Days + " days " : "") + LeadingZero(Hours) + ":" + LeadingZero(Minutes) + ":" + LeadingZero(Seconds)
  Timer.innerHTML = TimeStr;
}

function LeadingZero(Time) {
  return(Time < 10) ? "0" + Time : +Time;
}
</script>

<?php 
$tomorrow  = mktime(0, 0, 0, date("m")  , date("d")+1, date("Y"));
$currentTime = time();
$today = $tomorrow - $currentTime;
?>

<div id="timer"></div>

<script type="text/javascript">
  var today = <?php echo $today; ?>
  window.onload = CreateTimer("timer", today);
</script>

<div id="timer2"></div>

<script type="text/javascript">
  var today = <?php echo $today; ?>
  window.onload = CreateTimer("timer2", today);
</script>

2 个答案:

答案 0 :(得分:2)

它滴答速度快两倍的原因是两个倒计时共享相同的TotalSeconds变量。

答案 1 :(得分:1)

以下是如何制作独立计时器的示例。参数传递给start,它们可能更好地传递给getTimerinit函数。还可以随时调用stop方法停止计时器,可以轻松添加clearrestart方法。

function getTimer() {
  var el, currentNum, lag, timerRef;

  function start(id, startNum, delay) {
    el = document.getElementById(id);
    currentNum = startNum;
    lag = delay;
    run();
  }

  function run() {
    if (timerRef) stop();
    el.innerHTML = currentNum;
    if (currentNum--) {
      timerRef = setTimeout(run, lag);
    }
  }

  function stop() {
    if (timerRef) clearTimeout(timerRef);
  }

  return {
    start: start,
    run: run, 
    stop: stop
  };
}

window.onload = function() {

  var t0 = getTimer();
  t0.start('d0', 10, 1000);

  var t1 = getTimer();
  t1.start('d1', 20, 500);

  var t2 = getTimer();
  t2.start('d2', 40, 250);
}

HTML:

<div id="d0"></div>
<div id="d1"></div>
<div id="d2"></div>