Jquery倒计时器仅在页面上加载一次

时间:2014-08-07 20:25:45

标签: javascript jquery timer

大家都试图解决在我到达之前写的一些Jquery(我不是javascript大师)我基本上试图用相同的HTMl元素(不同的id)在页面上的另一个地方复制该函数javascript是如下:

enter code here<script type="text/javascript">
    // set minutes
var mins = 5;

// calculate the seconds (don't change this! unless time progresses at a different
var secs = mins * 60;
function countdown() {
setTimeout('Decrement()',1000);
}
function Decrement() {
if (document.getElementById) {
minutes = document.getElementById("minutes");
seconds = document.getElementById("seconds");
// if less than a minute remaining
if (seconds < 59) {
seconds.value = secs;
} else {
minutes.value = getminutes();
seconds.value = getseconds();
}
secs--;
setTimeout('Decrement()',1000);
}
}
function getminutes() {
// minutes is seconds divided by 60, rounded down
mins = Math.floor(secs / 60);
return mins;
}
function getseconds() {
// take mins remaining (as seconds) away from total seconds remaining
return secs-Math.round(mins *60);
}
</script>
<!-- /Countdown start -->

我的目标是使用同样的功能创建第二个计时器显示正在运行的计时器的HTML

<div class="timer-order timer" id="" >
                Expires In <input id="minutes" class="timer-order-text"> minutes <input id="seconds" class="timer-text22 timer-order-text"> seconds.
                <script>countdown();</script>
            </div>

这可能是一个新手问题,但是我可以复制用新id替换id的函数并使其工作吗?什么是使用.getelementbyID时复制相同函数的正确方法谢谢!

3 个答案:

答案 0 :(得分:1)

我将代码翻译成更多“可恢复”的组件

http://jsbin.com/gijanera/1/edit?html,js,output

当DOM准备就绪时,您可能应该加载它,因此在您的代码中,您可以在外部或代码中引用Timer函数。然后当加载DOM时(不确定你是否使用jquery)你会把它放在脚本标签之间......

<script>

    var initMinutes = 5,
        timer = new Timer( "insertMinutesId", "insertSecondsId", initMinutes );

    timer.start();

</script>

答案 1 :(得分:0)

setTimeout()只执行一次。您想要使用setInterval()。

有关详细信息,请参阅http://www.w3schools.com/js/js_timing.asp

答案 2 :(得分:0)

可能你使用它,添加注释以便于理解,在5*60000中,5表示分钟数。这是 DEMO

// set the date we're counting down to
var target_date = new Date().getTime() +5*60000;

// variables for time units
var days, hours, minutes, seconds;

// get tag element
var countdown = document.getElementById("countdown");

// update the tag with id "countdown" every 1 second
setInterval(function () {

    // find the amount of "seconds" between now and target
    var current_date = new Date().getTime();
    var seconds_left = (target_date - current_date) / 1000;

    // do some time calculations
    days = parseInt(seconds_left / 86400);
    seconds_left = seconds_left % 86400;

    hours = parseInt(seconds_left / 3600);
    seconds_left = seconds_left % 3600;

    minutes = parseInt(seconds_left / 60);
    seconds = parseInt(seconds_left % 60);

    // format countdown string + set tag value
    countdown.innerHTML = days + "d, " + hours + "h, "
    + minutes + "m, " + seconds + "s";  

    if(days== 0 && hours== 0 && minutes==0 && seconds==0)
stopTimer(); 

}, 1000);

//to stop timer
function stopTimer() {
    clearInterval(myVar);
}
相关问题