响应我命令的倒数计时器

克里斯·霍尔特

我正在尝试在JavaScript中创建一个倒数计时器,特别是可以设置为一分钟或两分钟的计时器,以及它的启动时间。

这是我能够从头开始完成的工作,但是我似乎无法使其正常工作:

var tim = 90
var min = (tim / 60) >> 0;
var sec = tim % 60;
function set1() {
    tim=60;
}
function set2() {
    tim=120;
}
function start() { function{ setInterval(function(){ tim-1; }, 1000);
}
function display() {

document.getElementById("demo").innerHTML = min + ":" + sec ;
}
<!DOCTYPE html>
<html>
<head>
</head>
<body onload="display()">


<p id="demo"></p>
<button onclick="set1()"> set one minute</button>
<button onclick="set2()"> set two minute</button>
<button onclick="start()"> start </button>
</body>
</html>

我也曾尝试从此处改编以下解决方案但无济于事。

function startTimer(duration, display) {
    var start = Date.now(),
        diff,
        minutes,
        seconds;
    function timer() {
        // get the number of seconds that have elapsed since 
        // startTimer() was called
        diff = duration - (((Date.now() - start) / 1000) | 0);

        // does the same job as parseInt truncates the float
        minutes = (diff / 60) | 0;
        seconds = (diff % 60) | 0;

        minutes = minutes < 10 ? "0" + minutes : minutes;
        seconds = seconds < 10 ? "0" + seconds : seconds;

        display.textContent = minutes + ":" + seconds; 

        if (diff <= 0) {
            // add one second so that the count down starts at the full duration
            // example 05:00 not 04:59
            start = Date.now() + 1000;
        }
    };
    // we don't want to wait a full second before the timer starts
    timer();
    setInterval(timer, 1000);
}

window.onload = function () {
    var fiveMinutes = 60 * 5,
        display = document.querySelector('#time');
    startTimer(fiveMinutes, display);
};
<body>
    <div>Registration closes in <span id="time"></span> minutes!</div>
</body>

我在这里想念什么?

阿达什·莫汉(Adarsh Mohan)

一个更简单的..

var TimerTime;
function startTimer(timerVal){
	clearInterval(TimerTime); //Only if you need to change the time
	var MIN = timerVal/60;
	var SEC = timerVal%60;
	TimerTime = setInterval(function(){
		SEC--;
		if(SEC<0){MIN--;SEC = 59;}
		if(MIN<0){clearInterval(TimerTime)}	
		else{
			document.getElementById("timerDisplay").innerHTML = MIN+" : "+SEC+" remaining...";
		}
	},1000);
}
window.onload = startTimer(60);
<select onchange="startTimer(this.value)">
  <option value="">Select Time</option>
  <option value="60">1 Minute</option>
  <option value="120">2 Minuts</option>
</select>
<div id="timerDisplay"></div>

本文收集自互联网,转载请注明来源。

如有侵权,请联系 [email protected] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章