无法弄清楚Javascript倒计时

时间:2013-03-04 15:30:13

标签: javascript

我需要帮助制作倒数计时器!

用户在文本字段中键入值,定时器在单击按钮时启动。

计时器文本每秒减少一次,直到达到零。

我有第一步的代码,但似乎无法完成第二步。我知道它需要包含一个setTimeout和loop。

到目前为止,这是代码:

HTML -

<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />


</head>
<body>



<div id="form">

<h2> COUNTDOWN</h2>

    Seconds: <input type="text" name="seconds" id="seconds" /> <input type="button" value="Start!" id="start" /> <input type="button" value="Pause" id="pause"  />
</div>


<div id="info">


</div>


<div id="countdown">


</div>

<script src="script.js"></script>
</body>
</html>

JAVASCRIPT -

window.onload = function(){

var startButton = document.getElementById("start");

var form = document.getElementById("seconds");

var pause = document.getElementById("pause");

var secDiv = document.getElementById("countdown");

var editSec = document.createElement("h1");


startButton.onclick = function (){

editSec.innerHTML = form.value;
secDiv.appendChild(editSec);


};


};

4 个答案:

答案 0 :(得分:1)

这就是:

var globalTime = form.value; //receive the timer from the form
var secDiv = document.getElementById("countdown");

function decreaseValue() {
  globalTime = globalTime - 1;

   secDiv.innerHTML = globalTime;
}

startButton.onclick = function (){
  setTimeout(decreasValue(),1000);
};

//clear out the timers once completed

答案 1 :(得分:0)

您需要使用setInterval,而不是setTimeout。将此代码添加到onclick函数:

editSec.id = "editSec";
window.cdint = setInterval(function(){ 
    var origVal = parseInt(document.getElementById("editSec").innerHTML);
    document.getElementById("editSec").innerHTML = origVal - 1;
    if(origVal - 1 <= 0){
        window.cdint = clearInterval(window.cdint);
    }
}, 1000);

答案 2 :(得分:0)

使用setInterval

var time = 100;
var countdown = function(){
    secdiv.innerHTML = time;
    time--;
}
setInterval(countdown,1000);

答案 3 :(得分:0)

如果您愿意,可以使用setTimeout

startButton.onclick = function () {
    var value = parseInt(form.value);
    editSec.innerHTML = value;
    secDiv.appendChild(editSec);
    setTimeout(function () {
        editSec.innerHTML = --value < 10
            ? '<span style="color:red">' + value + '</span>'
            : value;
        if (value) {
            setTimeout(arguments.callee, 1000);
        }
    }, 1000);
};