一个简单的 JavaScript 倒计时器的代码?

我想使用一个简单的倒计时计时器从30秒开始,从函数运行到0结束。没有毫秒。怎么可能被编码?

337611 次浏览
var count=30;


var counter=setInterval(timer, 1000); //1000 will  run it every 1 second


function timer()
{
count=count-1;
if (count <= 0)
{
clearInterval(counter);
//counter ended, do something here
return;
}


//Do code for showing the number of seconds here
}

要让计时器的代码出现在一个段落中(或者页面上的其他任何地方) ,只需要写下:

<span id="timer"></span>

你想让秒出现的地方。然后在 timer()函数中插入以下代码行,使它看起来像这样:

function timer()
{
count=count-1;
if (count <= 0)
{
clearInterval(counter);
return;
}


document.getElementById("timer").innerHTML=count + " secs"; // watch for spelling
}

不久前我写了这个剧本:

用法:

var myCounter = new Countdown({
seconds:5,  // number of seconds to count down
onUpdateStatus: function(sec){console.log(sec);}, // callback for each second
onCounterEnd: function(){ alert('counter ended!');} // final action
});


myCounter.start();

function Countdown(options) {
var timer,
instance = this,
seconds = options.seconds || 10,
updateStatus = options.onUpdateStatus || function () {},
counterEnd = options.onCounterEnd || function () {};


function decrementCounter() {
updateStatus(seconds);
if (seconds === 0) {
counterEnd();
instance.stop();
}
seconds--;
}


this.start = function () {
clearInterval(timer);
timer = 0;
seconds = options.seconds;
timer = setInterval(decrementCounter, 1000);
};


this.stop = function () {
clearInterval(timer);
};
}

到目前为止,答案似乎依赖于立即运行代码。如果您将计时器设置为1000ms,那么实际上它将在1008左右。

你应该这样做:

function timer(time,update,complete) {
var start = new Date().getTime();
var interval = setInterval(function() {
var now = time-(new Date().getTime()-start);
if( now <= 0) {
clearInterval(interval);
complete();
}
else update(Math.floor(now/1000));
},100); // the smaller this number, the more accurate the timer will be
}

使用,呼叫:

timer(
5000, // milliseconds
function(timeleft) { // called every step to update the visible countdown
document.getElementById('timer').innerHTML = timeleft+" second(s)";
},
function() { // what to do after
alert("Timer complete!");
}
);

// Javascript Countdown
// Version 1.01 6/7/07 (1/20/2000)
// by TDavid at http://www.tdscripts.com/
var now = new Date();
var theevent = new Date("Sep 29 2007 00:00:01");
var seconds = (theevent - now) / 1000;
var minutes = seconds / 60;
var hours = minutes / 60;
var days = hours / 24;
ID = window.setTimeout("update();", 1000);


function update() {
now = new Date();
seconds = (theevent - now) / 1000;
seconds = Math.round(seconds);
minutes = seconds / 60;
minutes = Math.round(minutes);
hours = minutes / 60;
hours = Math.round(hours);
days = hours / 24;
days = Math.round(days);
document.form1.days.value = days;
document.form1.hours.value = hours;
document.form1.minutes.value = minutes;
document.form1.seconds.value = seconds;
ID = window.setTimeout("update();", 1000);
}
<p><font face="Arial" size="3">Countdown To January 31, 2000, at 12:00: </font>
</p>
<form name="form1">
<p>Days
<input type="text" name="days" value="0" size="3">Hours
<input type="text" name="hours" value="0" size="4">Minutes
<input type="text" name="minutes" value="0" size="7">Seconds
<input type="text" name="seconds" value="0" size="7">
</p>
</form>

如果有人需要的话,这里还有一个:

    var mins = 10;  //Set the number of minutes you need
var secs = mins * 60;
var currentSeconds = 0;
var currentMinutes = 0;
/*
* The following line has been commented out due to a suggestion left in the comments. The line below it has not been tested.
* setTimeout('Decrement()',1000);
*/
setTimeout(Decrement,1000);


function Decrement() {
currentMinutes = Math.floor(secs / 60);
currentSeconds = secs % 60;
if(currentSeconds <= 9) currentSeconds = "0" + currentSeconds;
secs--;
document.getElementById("timerText").innerHTML = currentMinutes + ":" + currentSeconds; //Set the element id you need the time put into.
if(secs !== -1) setTimeout('Decrement()',1000);
}

您可以使用纯 JS 执行以下操作。你只需要给这个函数提供秒数,它就会完成剩下的工作。

var insertZero = n => n < 10 ? "0"+n : ""+n,
displayTime = n => n ? time.textContent = insertZero(~~(n/3600)%3600) + ":" +
insertZero(~~(n/60)%60) + ":" +
insertZero(n%60)
: time.textContent = "IGNITION..!",
countDownFrom = n => (displayTime(n), setTimeout(_ => n ? sid = countDownFrom(--n)
: displayTime(n), 1000)),
sid;
countDownFrom(3610);
setTimeout(_ => clearTimeout(sid),20005);
<div id="time"></div>

扩展已接受的答案,你的机器进入睡眠状态等可能会延迟计时器的工作。你可以得到一个真实的时间,代价是一点点的处理。这将给真正的剩余时间。

<span id="timer"></span>


<script>
var now = new Date();
var timeup = now.setSeconds(now.getSeconds() + 30);
//var timeup = now.setHours(now.getHours() + 1);


var counter = setInterval(timer, 1000);


function timer() {
now = new Date();
count = Math.round((timeup - now)/1000);
if (now > timeup) {
window.location = "/logout"; //or somethin'
clearInterval(counter);
return;
}
var seconds = Math.floor((count%60));
var minutes = Math.floor((count/60) % 60);
document.getElementById("timer").innerHTML = minutes + ":" + seconds;
}
</script>

基于@Layton Everson 提出的解决方案,我开发了一个包括小时、分钟和秒的计数器:

var initialSecs = 86400;
var currentSecs = initialSecs;


setTimeout(decrement,1000);


function decrement() {
var displayedSecs = currentSecs % 60;
var displayedMin = Math.floor(currentSecs / 60) % 60;
var displayedHrs = Math.floor(currentSecs / 60 /60);


if(displayedMin <= 9) displayedMin = "0" + displayedMin;
if(displayedSecs <= 9) displayedSecs = "0" + displayedSecs;
currentSecs--;
document.getElementById("timerText").innerHTML = displayedHrs + ":" + displayedMin + ":" + displayedSecs;
if(currentSecs !== -1) setTimeout(decrement,1000);
}

// Javascript Countdown
// Version 1.01 6/7/07 (1/20/2000)
// by TDavid at http://www.tdscripts.com/
var now = new Date();
var theevent = new Date("Nov 13 2017 22:05:01");
var seconds = (theevent - now) / 1000;
var minutes = seconds / 60;
var hours = minutes / 60;
var days = hours / 24;
ID = window.setTimeout("update();", 1000);


function update() {
now = new Date();
seconds = (theevent - now) / 1000;
seconds = Math.round(seconds);
minutes = seconds / 60;
minutes = Math.round(minutes);
hours = minutes / 60;
hours = Math.round(hours);
days = hours / 24;
days = Math.round(days);
document.form1.days.value = days;
document.form1.hours.value = hours;
document.form1.minutes.value = minutes;
document.form1.seconds.value = seconds;
ID = window.setTimeout("update();", 1000);
}
<p><font face="Arial" size="3">Countdown To January 31, 2000, at 12:00: </font>
</p>
<form name="form1">
<p>Days
<input type="text" name="days" value="0" size="3">Hours
<input type="text" name="hours" value="0" size="4">Minutes
<input type="text" name="minutes" value="0" size="7">Seconds
<input type="text" name="seconds" value="0" size="7">
</p>
</form>

我的解决方案使用 MySQL 日期时间格式,并提供了一个回调函数。 免责声明: 工程只与分钟和秒,因为这是我所需要的。

jQuery.fn.countDownTimer = function(futureDate, callback){
if(!futureDate){
throw 'Invalid date!';
}


var currentTs = +new Date();
var futureDateTs = +new Date(futureDate);


if(futureDateTs <= currentTs){
throw 'Invalid date!';
}




var diff = Math.round((futureDateTs - currentTs) / 1000);
var that = this;


(function countdownLoop(){
// Get hours/minutes from timestamp
var m = Math.floor(diff % 3600 / 60);
var s = Math.floor(diff % 3600 % 60);
var text = zeroPad(m, 2) + ':' + zeroPad(s, 2);


$(that).text(text);


if(diff <= 0){
typeof callback === 'function' ? callback.call(that) : void(0);
return;
}


diff--;
setTimeout(countdownLoop, 1000);
})();


function zeroPad(num, places) {
var zero = places - num.toString().length + 1;
return Array(+(zero > 0 && zero)).join("0") + num;
}
}


// $('.heading').countDownTimer('2018-04-02 16:00:59', function(){ // on complete})

刚刚修改过的 @ 点击上传的答案:

你可以使用 < strong > IIFE (立即调用函数表达式)和递归来使它更容易一点:

var i = 5;  //set the countdown
(function timer(){
if (--i < 0) return;
setTimeout(function(){
console.log(i + ' secs');  //do stuff here
timer();
}, 1000);
})();

var i = 5;
(function timer(){
if (--i < 0) return;
setTimeout(function(){
document.getElementsByTagName('h1')[0].innerHTML = i + ' secs';
timer();
}, 1000);
})();
<h1>5 secs</h1>

为了提高性能,我们现在可以安全地使用 RequestAnimationFrame进行快速循环,而不是使用 setInterval/setTimeout。

在使用 setInterval/setTimeout 时,如果循环任务花费的时间超过了间隔时间,浏览器将简单地扩展间隔循环,以继续完整的呈现。这是在制造麻烦。在 SetInterval/setTimeout 超载,这可以冻结选项卡、浏览器或整个计算机。的几分钟后

因特网设备的性能范围很广,所以不可能以毫秒为单位硬编码固定的间隔时间!

使用 日期对象,比较开始日期时代和当前。这比其他任何事情都要快,浏览器会在稳定的 60 FPS(1000/60 = 每帧16.66毫秒)-四分之一的眨眼时间状态下处理所有事情,如果循环中的任务需要更多,浏览器会丢掉一些重绘。

这允许在我们的眼睛注意到之前留出空白(人 = 24新兵 = > 1000/24 = 41.66 ms by frame = 流体动画!)

Https://caniuse.com/#search=requestanimationframe

/* Seconds to (STRING)HH:MM:SS.MS ------------------------*/
/* This time format is compatible with FFMPEG ------------*/
function secToTimer(sec){
const o = new Date(0), p =  new Date(sec * 1000)
return new Date(p.getTime()-o.getTime()).toString().split(" ")[4] + "." + p.getMilliseconds()
}


/* Countdown loop ----------------------------------------*/
let job, origin = new Date().getTime()
const timer = () => {
job = requestAnimationFrame(timer)
OUT.textContent = secToTimer((new Date().getTime() - origin) / 1000)
}


/* Start looping -----------------------------------------*/
requestAnimationFrame(timer)


/* Stop looping ------------------------------------------*/
// cancelAnimationFrame(job)


/* Reset the start date ----------------------------------*/
// origin = new Date().getTime()
span {font-size:4rem}
<span id="OUT"></span>
<br>
<button onclick="origin = new Date().getTime()">RESET</button>
<button onclick="requestAnimationFrame(timer)">RESTART</button>
<button onclick="cancelAnimationFrame(job)">STOP</button>

var hr = 0;
var min = 0;
var sec = 0;
var count = 0;
var flag = false;




function start(){
flag = true;
stopwatch();




}
function stop(){
flag = false;


}


function reset(){
flag = false;
hr = 0;
min = 0;
sec = 0;
count = 0;
document.getElementById("hr").innerHTML = "00";
document.getElementById("min").innerHTML = "00";
document.getElementById("sec").innerHTML = "00";
document.getElementById("count").innerHTML = "00";


}






function stopwatch(){
if(flag == true){
count = count + 1;
setTimeout( 'stopwatch()', 10);


if(count ==100){
count =0;
sec = sec +1;


}
}


if(sec ==60){
min = min +1 ;
sec = 0;


}
if(min == 60){
hr = hr +1 ;
min = 0;
sec = 0;


}
var hrs = hr;
var mins = min;
var secs = sec;
if(hr<10){
hrs ="0" + hr;


}
if(min<10){
mins ="0" + min;


}
if(sec<10){
secs ="0" + sec;


}
document.getElementById("hr").innerHTML = hrs;
document.getElementById("min").innerHTML = mins;
document.getElementById("sec").innerHTML = secs;
document.getElementById("count").innerHTML = count;
      

}