添加分钟或秒到Javascript倒计时器?

时间:2013-09-16 15:16:04

标签: javascript

我有一个javascript倒计时器。我需要做的是能够在倒数计时器运行时向计时器添加1分钟或几秒钟!

例如:如果我将分钟设置为1分钟并按下“开始”按钮,倒数计时器将按原样启动,但如果我在计时器运行时再添加一分钟,即当它在32秒时,它将不会将值添加到当前数字,它将继续倒计时加上前1分钟的剩余时间,它所做的只是因为某种原因加快了倒计时!

我希望我没有让你们困惑。 这是代码:

<form>
Minutes: <input type="text" id="mns" name="mns" value="0" size="3" maxlength="3" /> &nbsp; &nbsp; Seconds: <input type="text" id="scs" name="scs" value="0" size="2" maxlength="2" /><br/>
<input type="button" id="btnct" value="START" onclick="countdownTimer()"/>
</form>
Countdown Timer: &nbsp; <span id="showmns">00</span>:<span id="showscs">00</span>
<script type="text/javascript"><!--
    /* Function to display a Countdown timer with starting time from a form */
// sets variables for minutes and seconds
var ctmnts = 0;
var ctsecs = 0;
var startchr = 0;       // used to control when to read data from form

function countdownTimer() {
  // http://coursesweb.net/javascript/
  // if $startchr is 0, and form fields exists, gets data for minutes and seconds, and sets $startchr to 1
  if(startchr == 0 && document.getElementById('mns') && document.getElementById('scs')) {
    // makes sure the script uses integer numbers
    ctmnts = parseInt(document.getElementById('mns').value) + 0;
    ctsecs = parseInt(document.getElementById('scs').value) * 1;

    // if data not a number, sets the value to 0
    if(isNaN(ctmnts)) ctmnts = 0;
    if(isNaN(ctsecs)) ctsecs = 0;

    // rewrite data in form fields to be sure that the fields for minutes and seconds contain integer number
    document.getElementById('mns').value = ctmnts;
    document.getElementById('scs').value = ctsecs;
    startchr = 1;
  }

  // if minutes and seconds are 0, sets $startchr to 0, and return false
  if(ctmnts==0 && ctsecs==0) {
    startchr = 0;
    document.getElementById('btnct').removeAttribute('disabled');     // remove "disabled" to enable the button

    /* HERE YOU CAN ADD TO EXECUTE A JavaScript FUNCTION WHEN COUNTDOWN TIMER REACH TO 0 */

    return false;
  }
  else {
    // decrease seconds, and decrease minutes if seconds reach to 0
    ctsecs--;
    if(ctsecs < 0) {
      if(ctmnts > 0) {
        ctsecs = 59;
        ctmnts--;
      }
      else {
        ctsecs = 0;
        ctmnts = 0;
      }
    }
  }

  // display the time in page, and auto-calls this function after 1 seccond
  document.getElementById('showmns').innerHTML = ctmnts;
  document.getElementById('showscs').innerHTML = ctsecs;
  setTimeout('countdownTimer()', 1000);
}
//-->
</script>

任何帮助将不胜感激。

And here is the fiddle

1 个答案:

答案 0 :(得分:1)

将计数器编号视为要经过的总秒数的单个值,并且只关注转换为当前值和/或从当前值转换时的分钟和秒数(即,在获取初始输入时,或显示当前值时)。

请参阅http://jsfiddle.net/alnitak/aBWce/以获取一个可以避免需要检查每分钟结尾的工作示例,或填充数字的特殊情况。

顺便说一句,你的return false行是无操作的 - 回调函数的返回值被忽略。