2014-12-29 301 views
0

我目前有一個計時器,允許用戶選擇多長時間,他們希望定時器的倒計時。我想要發生的只是計時器在兩分鐘後開始,並在用戶單擊開始按鈕時開始倒計時。這裏是我的代碼消除輸入,啓動計時器在2分鐘

<body> 
<div id="countdown"></div> 
<div id="notifier"></div> 
<script type="text/javascript"> 
function startTimer() { 
userInput = document.getElementById('userTime').value; 
if(userInput.length == 0){ 
    alert("Please enter a value"); 
} else { 
var numericExpression = /^[0-9]+$/; 
if(!userInput.match(numericExpression)){ 
alert("Please enter a number") 
} else { 

function display(notifier, str) { 
document.getElementById(notifier).innerHTML = str; 
} 

function toMinuteAndSecond(x) { 
return Math.floor(x/60) + ":" + x%60; 
} 

function setTimer(remain, actions) { 
(function countdown() { 
    display("countdown", toMinuteAndSecond(remain));   
    actions[remain] && actions[remain](); 
    (remain -= 1) >= 0 && setTimeout(arguments.callee, 1000); 
})(); 
} 

setTimer(userInput, { 
10: function() { display("notifier", "Just 10 seconds to go"); }, 
5: function() { display("notifier", "5 seconds left");  }, 
0: function() { alert("Time is up. Please Sumbit Vote.");  } 
}); 
} 
} 
} 
</script> 
Set Time Limit: <input type="text" id="userTime" /> 
<input type="button" value="Start" onclick="startTimer()" /> 
</body> 

繼承人小提琴http://jsfiddle.net/grahamwalsh/0h9t65bs/

+0

當我寫2時,你的小提琴會計數2秒,所以當我寫2時,你想從2分鐘開始計數? –

+0

我不想要任何輸入,我只想讓它成爲一個2分鐘的計時器 – guyman

+0

然後硬編碼2分鐘而不是'document.getElementById('userTime').value'並放棄所有檢查。 – Teemu

回答

0

嘗試this小提琴

function startTimer() { 
    userInput = 120; 
    if(userInput.length == 0){ 
     alert("Please enter a value"); 
    } else { 
    var numericExpression = /^[0-9]+$/; 

    function display(notifier, str) { 
    document.getElementById(notifier).innerHTML = str; 
    } 

    function toMinuteAndSecond(x) { 
    return Math.floor(x/60) + ":" + x%60; 
    } 

    function setTimer(remain, actions) { 
    (function countdown() { 
     display("countdown", toMinuteAndSecond(remain));   
     actions[remain] && actions[remain](); 
     (remain -= 1) >= 0 && setTimeout(arguments.callee, 1000); 
    })(); 
    } 

    setTimer(userInput, { 
    10: function() { display("notifier", "Just 10 seconds to go"); }, 
    5: function() { display("notifier", "5 seconds left");  }, 
    0: function() { alert("Time is up. Please Sumbit Vote.");  } 
    }); 

} 
} 
document.addEventListener("DOMContentLoaded", function(event) { 
    startTimer(); 
}); 

update與啓動按鈕

添加

<input type="button" onclick="startTimer()" value="Start"> 
+0

這正是我想要的,除了我想要一個開始按鈕,我將如何去添加? – guyman

+0

我已經更新了我的答案,並提供了新的提琴鏈接,如果我的答案解決了您的問題,請告知我 – faby

+0

記得標記爲已接受,以避免問題仍未解答 – faby