[英]Recursive countdown timer
I'm trying to create a javascript counter that starts at 25 minutes and ends at 0. the idea is to show the minutes/seconds as a countdown clock on the page (my target div is called 'txt'). 我正在尝试创建一个JavaScript计数器,该计数器的开始时间为25分钟,结束于0。其想法是在页面上将倒数时钟显示为分钟/秒(我的目标div称为“ txt”)。 But I'm not getting my desired result - the timer does not subtract each time the function is run (every ms).
但是我没有得到我想要的结果-计时器不会在函数每次运行时减去(每毫秒)。 Any ideas on where I'm going wrong?
关于我要去哪里的任何想法? Code is below:
代码如下:
function countdown() {
var target = 1500000; // 25 mins
var current = 1000; // 0 secs
for (var i=0; i<5; i++) {
var diff = target-current; // calculates the 25 minutes
var min = Math.floor(diff/1000/60); //gets mins
var sec = (diff/1000) % 60; // gets secs
current = current+1000;
document.getElementById("txt").innerHTML = min + ":" + sec;
var t = setTimeout(countdown, 2500);}
}
}
You need to define current outside of your function. 您需要在函数之外定义当前函数。 Currently you are resetting it to 1000 every time the function is run.
当前,每次运行该功能时,它将重置为1000。
here you go: 干得好:
var target = 1500000; // 25 mins
var current = 0; // 0 secs
function countdown() {
current += 1000;
var diff = target-current; // calculates the 25 minutes
var min = Math.floor(diff/1000/60); //gets mins
var sec = (diff/1000) % 60; // gets secs
document.getElementById("txt").innerHTML = min + ":" + sec;
if (diff > 0)
setTimeout(countdown, 1000);
}
countdown();
JSFiddle with running example: https://jsfiddle.net/epcmw0uc/5/ 具有运行示例的JSFiddle: https ://jsfiddle.net/epcmw0uc/5/
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.