目前我正在尝试创建一个minutes:second
计时器,方法是让用户在几分钟内输入textbox2
文本框所需的时长,但当我尝试执行get.ElementbyID.value
时变量mins,它不起作用并给出错误(NULL error
),因为我尝试全局变量也不起作用。
我要求用户能够在几分钟内输入文本框,按下开始按钮将开始用户请求的时间。
var mins = 1;
var secs = mins * 60;
var currentSeconds = 0;
var currentMinutes = 0;
function start2() {
start();
}
function start() {
setTimeout(Decrement, 1000)
}
function Decrement() {
currentMinutes = Math.floor(secs / 60);
currentSeconds = secs % 60;
if (currentSeconds <= 9) currentSeconds = "0" + currentSeconds;
secs--;
document.getElementById("timer").innerHTML = currentMinutes + ":" + currentSeconds; //Set the element id you need the time put into.
if (secs !== -1) {
setTimeout('Decrement()', 1000);
}
if (secs == -1) {
alert("hi");
}
}
<input type="text" id="textbox2" value="0"></input>
<br/>
<button onclick="start2();">Start Timer</button>
<br/>
<p id="timer"></p>
答案 0 :(得分:1)
我认为你的问题是你试图在页面加载时设置mins
变量。而是在start
函数中加载值。
您还需要在确定分钟后计算秒数。
var mins = 1;
var secs = mins * 60;
var currentSeconds = 0;
var currentMinutes = 0;
function start2() {
start();
}
function start() {
mins = document.getElementById('textbox2').value;
// set a default of 1 minute if it is less than one or not a number..
mins = isNaN(mins) || mins < 1 ? 1 : mins;
// calculate seconds down here, as well.
secs = mins * 60;
setTimeout(Decrement, 1000);
}
function Decrement() {
currentMinutes = Math.floor(secs / 60);
currentSeconds = secs % 60;
if (currentSeconds <= 9) currentSeconds = "0" + currentSeconds;
secs--;
document.getElementById("timer").innerHTML = currentMinutes + ":" + currentSeconds; //Set the element id you need the time put into.
if (secs !== -1) {
setTimeout('Decrement()', 1000);
}
if (secs == -1) {
alert("hi");
}
}
<input type="text" id="textbox2" value="0"></input>
<br/>
<button onclick="start2();">Start Timer</button>
<br/>
<p id="timer"></p>
答案 1 :(得分:0)
var secs = 0;
function start(s) {
secs = s;
schedule();
}
function schedule() {
setTimeout(Decrement, 1000)
}
function Decrement() {
var currentMinutes = Math.floor(secs / 60);
var currentSeconds = secs % 60;
if (currentSeconds <= 9) currentSeconds = "0" + currentSeconds;
document.getElementById("timer").innerHTML = currentMinutes + ":" + currentSeconds;
if (secs-- > 0 )
schedule()
else
alert("hi");
}
<input type="text" id="textbox2" value="0"></input>
<br/>
<button onclick="start( parseInt( document.getElementById('textbox2').value ) );">Start Timer</button>
<br/>
<p id="timer"></p>